1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516 |
- /*##############################################################################
- HPCC SYSTEMS software Copyright (C) 2013 HPCC Systems®.
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ############################################################################## */
- #include "platform.h"
- #include "mysql.h"
- #include "jexcept.hpp"
- #include "jthread.hpp"
- #include "hqlplugins.hpp"
- #include "deftype.hpp"
- #include "eclhelper.hpp"
- #include "eclrtl.hpp"
- #include "eclrtl_imp.hpp"
- #include "rtlds_imp.hpp"
- #include "rtlfield_imp.hpp"
- #include "rtlembed.hpp"
- #include "roxiemem.hpp"
- #include "nbcd.hpp"
- #ifdef _WIN32
- #define EXPORT __declspec(dllexport)
- #else
- #define EXPORT
- #endif
- __declspec(noreturn) static void UNSUPPORTED(const char *feature) __attribute__((noreturn));
- static void UNSUPPORTED(const char *feature)
- {
- throw MakeStringException(-1, "UNSUPPORTED feature: %s not supported in mysql plugin", feature);
- }
- static const char * compatibleVersions[] = {
- "MySQL Embed Helper 1.0.0",
- NULL };
- static const char *version = "MySQL Embed Helper 1.0.0";
- extern "C" EXPORT bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
- {
- if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
- {
- ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
- pbx->compatibleVersions = compatibleVersions;
- }
- else if (pb->size != sizeof(ECLPluginDefinitionBlock))
- return false;
- pb->magicVersion = PLUGIN_VERSION;
- pb->version = version;
- pb->moduleName = "mysql";
- pb->ECL = NULL;
- pb->flags = PLUGIN_MULTIPLE_VERSIONS;
- pb->description = "MySQL Embed Helper";
- return true;
- }
- namespace mysqlembed {
- __declspec(noreturn) static void failx(const char *msg, ...) __attribute__((format(printf, 1, 2), noreturn));
- __declspec(noreturn) static void fail(const char *msg) __attribute__((noreturn));
- static void failx(const char *message, ...)
- {
- va_list args;
- va_start(args,message);
- StringBuffer msg;
- msg.append("mysql: ").valist_appendf(message,args);
- va_end(args);
- rtlFail(0, msg.str());
- }
- static void fail(const char *message)
- {
- StringBuffer msg;
- msg.append("mysql: ").append(message);
- rtlFail(0, msg.str());
- }
- // Wrappers to MySQL structures that require corresponding releases
- class MySQLConnection : public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- MySQLConnection(MYSQL *_conn) : conn(_conn)
- {
- }
- ~MySQLConnection()
- {
- if (conn)
- mysql_close(conn);
- }
- inline operator MYSQL *() const
- {
- return conn;
- }
- private:
- MySQLConnection(const MySQLConnection &);
- MYSQL *conn;
- };
- class MySQLResult : public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- MySQLResult(MYSQL_RES *_res) : res(_res)
- {
- }
- ~MySQLResult()
- {
- if (res)
- mysql_free_result(res);
- }
- inline operator MYSQL_RES *() const
- {
- return res;
- }
- private:
- MySQLResult(const MySQLResult &);
- MYSQL_RES *res;
- };
- class MySQLStatement : public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- MySQLStatement(MYSQL_STMT *_stmt) : stmt(_stmt)
- {
- }
- ~MySQLStatement()
- {
- if (stmt)
- mysql_stmt_close(stmt);
- }
- inline operator MYSQL_STMT *() const
- {
- return stmt;
- }
- private:
- MySQLStatement(const MySQLStatement &);
- MYSQL_STMT *stmt;
- };
- class MySQLBindingArray
- {
- public:
- MySQLBindingArray()
- {
- columns = 0;
- bindinfo = NULL;
- is_null = NULL;;
- error = NULL;
- lengths = NULL;
- }
- void init(unsigned count)
- {
- columns = count;
- if (columns)
- {
- bindinfo = new MYSQL_BIND [columns];
- is_null = new my_bool [columns];
- error = new my_bool [columns];
- lengths = new unsigned long [columns];
- memset(bindinfo, 0, columns * sizeof(bindinfo[0]));
- memset(is_null, 0, columns * sizeof(is_null[0]));
- memset(error, 0, columns * sizeof(error[0]));
- memset(lengths, 0, columns * sizeof(lengths[0]));
- for (int i = 0; i < columns; i++)
- {
- bindinfo[i].is_null = &is_null[i];
- bindinfo[i].length = &lengths[i];
- bindinfo[i].error = &error[i];
- }
- }
- }
- void bindResults(MYSQL_RES *res)
- {
- init(mysql_num_fields(res));
- for (int i = 0; i < columns; i++)
- {
- MYSQL_FIELD *col = mysql_fetch_field_direct(res, i);
- switch (col->type)
- {
- case MYSQL_TYPE_DECIMAL:
- case MYSQL_TYPE_NEWDECIMAL:
- bindinfo[i].buffer_type = MYSQL_TYPE_STRING;
- bindinfo[i].buffer_length = 100; // MORE - is there a better guess?
- break;
- case MYSQL_TYPE_TIMESTAMP:
- case MYSQL_TYPE_DATETIME:
- case MYSQL_TYPE_TIME:
- case MYSQL_TYPE_DATE:
- bindinfo[i].buffer_type = col->type;
- bindinfo[i].buffer_length = sizeof(MYSQL_TIME);
- break;
- default:
- bindinfo[i].buffer_type = col->type;
- bindinfo[i].buffer_length = col->length;
- break;
- }
- bindinfo[i].buffer = rtlMalloc(bindinfo[i].buffer_length);
- }
- }
- ~MySQLBindingArray()
- {
- for (int i = 0; i < columns; i++)
- {
- rtlFree(bindinfo[i].buffer);
- }
- delete [] bindinfo;
- delete [] is_null;
- delete [] error;
- delete [] lengths;
- }
- inline int numColumns() const
- {
- return columns;
- }
- inline MYSQL_BIND &queryColumn(int colIdx, const char *name) const
- {
- if (colIdx >= columns)
- {
- VStringBuffer error("No matching bound column for parameter %d", colIdx);
- if (name)
- error.appendf(" (%s)", name);
- fail(error);
- }
- return bindinfo[colIdx];
- }
- inline MYSQL_BIND *queryBindings() const
- {
- return bindinfo;
- }
- private:
- MYSQL_BIND *bindinfo;
- my_bool *is_null;
- my_bool *error;
- unsigned long *lengths;
- int columns;
- };
- class MySQLPreparedStatement : public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- MySQLPreparedStatement(MySQLConnection *_conn, MySQLStatement *_stmt)
- : conn(_conn), stmt(_stmt)
- {
- // Create bindings for input parameters
- inputBindings.init(mysql_stmt_param_count(*stmt));
- // And for results
- res.setown(new MySQLResult(mysql_stmt_result_metadata(*stmt)));
- if (*res)
- {
- resultBindings.bindResults(*res);
- /* Bind the result buffers */
- if (mysql_stmt_bind_result(*stmt, resultBindings.queryBindings()))
- fail(mysql_stmt_error(*stmt));
- }
- else if (mysql_stmt_errno(*stmt)) // SQL actions don't return results...
- fail(mysql_stmt_error(*stmt));
- }
- ~MySQLPreparedStatement()
- {
- stop();
- }
- inline void stop()
- {
- res.clear();
- stmt.clear();
- }
- bool next()
- {
- if (!stmt)
- return false;
- int rc = mysql_stmt_fetch(*stmt);
- if (rc == MYSQL_NO_DATA)
- return false;
- else if (rc)
- fail(mysql_stmt_error(*stmt));
- else
- return true;
- }
- void execute()
- {
- assertex(stmt && *stmt);
- if (inputBindings.numColumns() && mysql_stmt_bind_param(*stmt, inputBindings.queryBindings()))
- fail(mysql_stmt_error(*stmt));
- if (mysql_stmt_execute(*stmt))
- fail(mysql_stmt_error(*stmt));
- }
- inline const MySQLBindingArray &queryResultBindings() const
- {
- return resultBindings;
- }
- inline const MySQLBindingArray &queryInputBindings() const
- {
- return inputBindings;
- }
- inline bool hasResult() const
- {
- return *res != NULL;
- }
- protected:
- Linked<MySQLConnection> conn;
- Linked<MySQLStatement> stmt;
- Owned<MySQLResult> res;
- MySQLBindingArray inputBindings;
- MySQLBindingArray resultBindings;
- };
- // Conversions from MySQL values to ECL data
- __declspec(noreturn) static void typeError(const char *expected, const RtlFieldInfo *field) __attribute__((noreturn));
- static void typeError(const char *expected, const RtlFieldInfo *field)
- {
- VStringBuffer msg("mysql: type mismatch - %s expected", expected);
- if (field)
- msg.appendf(" for field %s", field->name->queryStr());
- rtlFail(0, msg.str());
- }
- static bool isInteger(enum_field_types type)
- {
- switch (type)
- {
- case MYSQL_TYPE_TINY:
- case MYSQL_TYPE_SHORT:
- case MYSQL_TYPE_LONG:
- case MYSQL_TYPE_LONGLONG:
- case MYSQL_TYPE_INT24:
- return true;
- default:
- return false;
- }
- }
- static bool isDateTime(enum_field_types type)
- {
- switch (type)
- {
- case MYSQL_TYPE_TIMESTAMP:
- case MYSQL_TYPE_DATETIME:
- case MYSQL_TYPE_DATE:
- case MYSQL_TYPE_TIME:
- return true;
- default:
- return false;
- }
- }
- static bool isString(enum_field_types type)
- {
- switch (type)
- {
- case MYSQL_TYPE_TINY_BLOB:
- case MYSQL_TYPE_MEDIUM_BLOB:
- case MYSQL_TYPE_LONG_BLOB:
- case MYSQL_TYPE_BLOB:
- case MYSQL_TYPE_STRING:
- case MYSQL_TYPE_VAR_STRING:
- return true;
- default:
- return false;
- }
- }
- static unsigned __int64 getDateTimeValue(const MYSQL_BIND &bound)
- {
- const MYSQL_TIME * time = (const MYSQL_TIME *) bound.buffer;
- switch (bound.buffer_type)
- {
- case MYSQL_TYPE_TIMESTAMP:
- case MYSQL_TYPE_DATETIME:
- //What format should this be? Possibly a timestamp_t
- return (unsigned __int64)((time->year * 10000) + (time->month * 100) + (time->day)) * 1000000 +
- (time->hour * 10000) + (time->minute * 100) + (time->second);
- case MYSQL_TYPE_DATE:
- return (time->year * 10000) + (time->month * 100) + (time->day);
- case MYSQL_TYPE_TIME:
- return (time->hour * 10000) + (time->minute * 100) + (time->second);
- default:
- throwUnexpected();
- }
- }
- static void getDateTimeText(const MYSQL_BIND &bound, size32_t &chars, char * &result)
- {
- const MYSQL_TIME * time = (const MYSQL_TIME *) bound.buffer;
- char temp[20];
- switch (bound.buffer_type)
- {
- case MYSQL_TYPE_TIMESTAMP:
- case MYSQL_TYPE_DATETIME:
- _snprintf(temp, sizeof(temp), "%4u-%02u-%02u %02u:%02u:%02u", time->year, time->month, time->day, time->hour, time->minute, time->second);
- break;
- case MYSQL_TYPE_DATE:
- _snprintf(temp, sizeof(temp), "%4u-%02u-%02u", time->year, time->month, time->day);
- break;
- case MYSQL_TYPE_TIME:
- _snprintf(temp, sizeof(temp), "%02u:%02u:%02u", time->hour, time->minute, time->second);
- break;
- default:
- throwUnexpected();
- }
- rtlStrToStrX(chars, result, strlen(temp), temp);
- }
- static bool getBooleanResult(const RtlFieldInfo *field, const MYSQL_BIND &bound)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- return p.boolResult;
- }
- if (!isInteger(bound.buffer_type))
- typeError("boolean", field);
- return rtlReadUInt(bound.buffer, *bound.length) != 0;
- }
- static void getDataResult(const RtlFieldInfo *field, const MYSQL_BIND &bound, size32_t &chars, void * &result)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- rtlStrToDataX(chars, result, p.resultChars, p.stringResult);
- return;
- }
- if (isString(bound.buffer_type))
- rtlStrToDataX(chars, result, *bound.length, bound.buffer); // This feels like it may not work to me - will preallocate rather larger than we want
- else
- typeError("blob", field);
- }
- static __int64 getSignedResult(const RtlFieldInfo *field, const MYSQL_BIND &bound);
- static unsigned __int64 getUnsignedResult(const RtlFieldInfo *field, const MYSQL_BIND &bound);
- static double getRealResult(const RtlFieldInfo *field, const MYSQL_BIND &bound)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- return p.doubleResult;
- }
- if (isInteger(bound.buffer_type))
- {
- if (bound.is_unsigned)
- return (double) getUnsignedResult(field, bound);
- else
- return (double) getSignedResult(field, bound);
- }
- else if (bound.buffer_type == MYSQL_TYPE_FLOAT)
- return * (float *) bound.buffer;
- else if (bound.buffer_type == MYSQL_TYPE_DOUBLE)
- return * (double *) bound.buffer;
- else
- typeError("double", field);
- }
- static __int64 getSignedResult(const RtlFieldInfo *field, const MYSQL_BIND &bound)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- return p.intResult;
- }
- if (isDateTime(bound.buffer_type))
- return getDateTimeValue(bound);
- if (isInteger(bound.buffer_type))
- {
- if (bound.is_unsigned)
- return (__int64) rtlReadUInt(bound.buffer, *bound.length);
- else
- return rtlReadInt(bound.buffer, *bound.length);
- }
- else
- typeError("integer", field);
- }
- static unsigned __int64 getUnsignedResult(const RtlFieldInfo *field, const MYSQL_BIND &bound)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- return p.uintResult;
- }
- if (isDateTime(bound.buffer_type))
- return getDateTimeValue(bound);
- if (!isInteger(bound.buffer_type))
- typeError("integer", field);
- if (bound.is_unsigned)
- return rtlReadUInt(bound.buffer, *bound.length);
- else
- return (unsigned __int64) rtlReadInt(bound.buffer, *bound.length);
- }
- static void getStringResult(const RtlFieldInfo *field, const MYSQL_BIND &bound, size32_t &chars, char * &result)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- rtlStrToStrX(chars, result, p.resultChars, p.stringResult);
- return;
- }
- if (isDateTime(bound.buffer_type))
- {
- getDateTimeText(bound, chars, result);
- return;
- }
- if (!isString(bound.buffer_type))
- typeError("string", field);
- const char *text = (const char *) bound.buffer;
- unsigned long bytes = *bound.length;
- unsigned numchars = rtlUtf8Length(bytes, text); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think
- rtlUtf8ToStrX(chars, result, numchars, text);
- }
- static void getUTF8Result(const RtlFieldInfo *field, const MYSQL_BIND &bound, size32_t &chars, char * &result)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- rtlUtf8ToUtf8X(chars, result, p.resultChars, p.stringResult);
- return;
- }
- if (isDateTime(bound.buffer_type))
- {
- getDateTimeText(bound, chars, result);
- return;
- }
- if (!isString(bound.buffer_type))
- typeError("string", field);
- const char *text = (const char *) bound.buffer;
- unsigned long bytes = *bound.length;
- unsigned numchars = rtlUtf8Length(bytes, text); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think
- rtlUtf8ToUtf8X(chars, result, numchars, text);
- }
- static void getUnicodeResult(const RtlFieldInfo *field, const MYSQL_BIND &bound, size32_t &chars, UChar * &result)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- rtlUnicodeToUnicodeX(chars, result, p.resultChars, p.unicodeResult);
- return;
- }
- if (bound.buffer_type != MYSQL_TYPE_STRING && bound.buffer_type != MYSQL_TYPE_VAR_STRING)
- typeError("string", field);
- const char *text = (const char *) bound.buffer;
- unsigned long bytes = *bound.length;
- unsigned numchars = rtlUtf8Length(bytes, text); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think
- rtlUtf8ToUnicodeX(chars, result, numchars, text);
- }
- static void getDecimalResult(const RtlFieldInfo *field, const MYSQL_BIND &bound, Decimal &value)
- {
- if (*bound.is_null)
- {
- NullFieldProcessor p(field);
- value.set(p.decimalResult);
- return;
- }
- size32_t chars;
- rtlDataAttr result;
- mysqlembed::getStringResult(field, bound, chars, result.refstr());
- value.setString(chars, result.getstr());
- if (field)
- {
- RtlDecimalTypeInfo *dtype = (RtlDecimalTypeInfo *) field->type;
- value.setPrecision(dtype->getDecimalDigits(), dtype->getDecimalPrecision());
- }
- }
- static void createBindBuffer(MYSQL_BIND & bindInfo, enum_field_types sqlType, unsigned size)
- {
- if (size)
- {
- if (!bindInfo.buffer)
- {
- bindInfo.buffer_type = sqlType;
- bindInfo.buffer = rtlMalloc(size);
- }
- else
- assertex(bindInfo.buffer_type == sqlType);
- }
- else
- {
- // Buffer is reallocated each time - caller is responsible for it.
- bindInfo.buffer_type = sqlType;
- rtlFree(bindInfo.buffer);
- bindInfo.buffer = NULL;
- }
- }
- // A MySQLRowBuilder object is used to construct an ECL row from a MySQL row
- class MySQLRowBuilder : public CInterfaceOf<IFieldSource>
- {
- public:
- MySQLRowBuilder(const MySQLBindingArray &_resultInfo)
- : resultInfo(_resultInfo), colIdx(-1)
- {
- }
- virtual bool getBooleanResult(const RtlFieldInfo *field)
- {
- return mysqlembed::getBooleanResult(field, nextField(field));
- }
- virtual void getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result)
- {
- mysqlembed::getDataResult(field, nextField(field), len, result);
- }
- virtual double getRealResult(const RtlFieldInfo *field)
- {
- return mysqlembed::getRealResult(field, nextField(field));
- }
- virtual __int64 getSignedResult(const RtlFieldInfo *field)
- {
- return mysqlembed::getSignedResult(field, nextField(field));
- }
- virtual unsigned __int64 getUnsignedResult(const RtlFieldInfo *field)
- {
- return mysqlembed::getUnsignedResult(field, nextField(field));
- }
- virtual void getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result)
- {
- mysqlembed::getStringResult(field, nextField(field), chars, result);
- }
- virtual void getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result)
- {
- mysqlembed::getUTF8Result(field, nextField(field), chars, result);
- }
- virtual void getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result)
- {
- mysqlembed::getUnicodeResult(field, nextField(field), chars, result);
- }
- virtual void getDecimalResult(const RtlFieldInfo *field, Decimal &value)
- {
- mysqlembed::getDecimalResult(field, nextField(field), value);
- }
- virtual void processBeginSet(const RtlFieldInfo * field, bool &isAll)
- {
- UNSUPPORTED("SET fields");
- }
- virtual bool processNextSet(const RtlFieldInfo * field)
- {
- throwUnexpected();
- }
- virtual void processBeginDataset(const RtlFieldInfo * field)
- {
- UNSUPPORTED("Nested datasets");
- }
- virtual void processBeginRow(const RtlFieldInfo * field)
- {
- }
- virtual bool processNextRow(const RtlFieldInfo * field)
- {
- throwUnexpected();
- }
- virtual void processEndSet(const RtlFieldInfo * field)
- {
- throwUnexpected();
- }
- virtual void processEndDataset(const RtlFieldInfo * field)
- {
- throwUnexpected();
- }
- virtual void processEndRow(const RtlFieldInfo * field)
- {
- }
- protected:
- const MYSQL_BIND &nextField(const RtlFieldInfo * field)
- {
- if (colIdx < resultInfo.numColumns())
- colIdx++;
- else
- fail("Too many fields in ECL output row");
- const MYSQL_BIND &column = resultInfo.queryColumn(colIdx,field->name->queryStr());
- if (*column.error)
- failx("Error fetching column %s", field->name->queryStr());
- return column;
- }
- const MySQLBindingArray &resultInfo;
- int colIdx;
- };
- // Bind MySQL variables from an ECL record
- class MySQLRecordBinder : public CInterfaceOf<IFieldProcessor>
- {
- public:
- MySQLRecordBinder(const RtlTypeInfo *_typeInfo, const MySQLBindingArray &_bindings, int _firstParam)
- : typeInfo(_typeInfo), bindings(_bindings), firstParam(_firstParam), dummyField("<row>", NULL, typeInfo), thisParam(_firstParam)
- {
- }
- int numFields()
- {
- int count = 0;
- const RtlFieldInfo * const *fields = typeInfo->queryFields();
- assertex(fields);
- while (*fields++)
- count++;
- return count;
- }
- void processRow(const byte *row)
- {
- thisParam = firstParam;
- typeInfo->process(row, row, &dummyField, *this); // Bind the variables for the current row
- }
- virtual void processString(unsigned len, const char *value, const RtlFieldInfo * field)
- {
- size32_t utf8chars;
- char *utf8;
- rtlStrToUtf8X(utf8chars, utf8, len, value);
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = utf8;
- bindInfo.buffer_length = rtlUtf8Size(utf8chars, utf8);
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void processBool(bool value, const RtlFieldInfo * field)
- {
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_TINY, sizeof(value));
- * (bool *) bindInfo.buffer = value;
- bindInfo.is_unsigned = true;
- }
- virtual void processData(unsigned len, const void *value, const RtlFieldInfo * field)
- {
- size32_t bytes;
- void *data;
- rtlStrToDataX(bytes, data, len, value);
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_BLOB, 0);
- bindInfo.buffer = data;
- bindInfo.buffer_length = bytes;
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void processInt(__int64 value, const RtlFieldInfo * field)
- {
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_LONGLONG, sizeof(value));
- * (__int64 *) bindInfo.buffer = value;
- bindInfo.is_unsigned = false;
- }
- virtual void processUInt(unsigned __int64 value, const RtlFieldInfo * field)
- {
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_LONGLONG, sizeof(value));
- * (unsigned __int64 *) bindInfo.buffer = value;
- bindInfo.is_unsigned = true;
- }
- virtual void processReal(double value, const RtlFieldInfo * field)
- {
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_DOUBLE, sizeof(value));
- * (double *) bindInfo.buffer = value;
- }
- virtual void processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
- {
- Decimal val;
- size32_t bytes;
- char *data;
- val.setDecimal(digits, precision, value);
- val.getStringX(bytes, data);
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = data;
- bindInfo.buffer_length = bytes;
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void processUDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
- {
- Decimal val;
- size32_t bytes;
- char *data;
- val.setUDecimal(digits, precision, value);
- val.getStringX(bytes, data);
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = data;
- bindInfo.buffer_length = bytes;
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void processUnicode(unsigned len, const UChar *value, const RtlFieldInfo * field)
- {
- size32_t utf8chars;
- char *utf8;
- rtlUnicodeToUtf8X(utf8chars, utf8, len, value);
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = utf8;
- bindInfo.buffer_length = rtlUtf8Size(utf8chars, utf8);
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void processQString(unsigned len, const char *value, const RtlFieldInfo * field)
- {
- size32_t charCount;
- rtlDataAttr text;
- rtlQStrToStrX(charCount, text.refstr(), len, value);
- processString(charCount, text.getstr(), field);
- }
- virtual void processUtf8(unsigned len, const char *value, const RtlFieldInfo * field)
- {
- size32_t utf8chars;
- char *utf8;
- rtlUtf8ToUtf8X(utf8chars, utf8, len, value);
- MYSQL_BIND &bindInfo = createBindBuffer(MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = utf8;
- bindInfo.buffer_length = rtlUtf8Size(utf8chars, utf8);
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual bool processBeginSet(const RtlFieldInfo * field, unsigned numElements, bool isAll, const byte *data)
- {
- UNSUPPORTED("SET fields");
- return false;
- }
- virtual bool processBeginDataset(const RtlFieldInfo * field, unsigned numRows)
- {
- UNSUPPORTED("Nested datasets");
- return false;
- }
- virtual bool processBeginRow(const RtlFieldInfo * field)
- {
- return true;
- }
- virtual void processEndSet(const RtlFieldInfo * field)
- {
- throwUnexpected();
- }
- virtual void processEndDataset(const RtlFieldInfo * field)
- {
- throwUnexpected();
- }
- virtual void processEndRow(const RtlFieldInfo * field)
- {
- }
- protected:
- MYSQL_BIND &createBindBuffer(enum_field_types sqlType, unsigned size)
- {
- MYSQL_BIND &bindInfo = bindings.queryColumn(thisParam++, NULL);
- mysqlembed::createBindBuffer(bindInfo, sqlType, size);
- return bindInfo;
- }
- const RtlTypeInfo *typeInfo;
- const MySQLBindingArray &bindings;
- int firstParam;
- RtlFieldStrInfo dummyField;
- int thisParam;
- };
- //
- class MySQLDatasetBinder : public MySQLRecordBinder
- {
- public:
- MySQLDatasetBinder(IRowStream * _input, const RtlTypeInfo *_typeInfo, const MySQLBindingArray &_bindings, int _firstParam)
- : input(_input), MySQLRecordBinder(_typeInfo, _bindings, _firstParam)
- {
- }
- bool bindNext()
- {
- roxiemem::OwnedConstRoxieRow nextRow = (const byte *) input->ungroupedNextRow();
- if (!nextRow)
- return false;
- processRow((const byte *) nextRow.get()); // Bind the variables for the current row
- return true;
- }
- void executeAll(MySQLPreparedStatement *stmtInfo)
- {
- while (bindNext())
- {
- stmtInfo->execute();
- }
- }
- protected:
- Owned<IRowStream> input;
- };
- // A MySQL function that returns a dataset will return a MySQLRowStream object that can be
- // interrogated to return each row of the result in turn
- class MySQLRowStream : public CInterfaceOf<IRowStream>
- {
- public:
- MySQLRowStream(MySQLDatasetBinder *_inputStream, MySQLPreparedStatement *_stmtInfo, IEngineRowAllocator *_resultAllocator)
- : inputStream(_inputStream), stmtInfo(_stmtInfo), resultAllocator(_resultAllocator)
- {
- executePending = true;
- eof = false;
- }
- virtual const void *nextRow()
- {
- // A little complex when streaming data in as well as out - want to execute for every input record
- if (eof)
- return NULL;
- loop
- {
- if (executePending)
- {
- executePending = false;
- if (inputStream && !inputStream->bindNext())
- {
- noteEOF();
- return NULL;
- }
- stmtInfo->execute();
- }
- if (stmtInfo->next())
- break;
- if (inputStream)
- executePending = true;
- else
- {
- noteEOF();
- return NULL;
- }
- }
- RtlDynamicRowBuilder rowBuilder(resultAllocator);
- MySQLRowBuilder mysqlRowBuilder(stmtInfo->queryResultBindings());
- const RtlTypeInfo *typeInfo = resultAllocator->queryOutputMeta()->queryTypeInfo();
- assertex(typeInfo);
- RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
- size32_t len = typeInfo->build(rowBuilder, 0, &dummyField, mysqlRowBuilder);
- return rowBuilder.finalizeRowClear(len);
- }
- virtual void stop()
- {
- resultAllocator.clear();
- stmtInfo->stop();
- }
- protected:
- void noteEOF()
- {
- if (!eof)
- {
- eof = true;
- stop();
- }
- }
- Linked<MySQLDatasetBinder> inputStream;
- Linked<MySQLPreparedStatement> stmtInfo;
- Linked<IEngineRowAllocator> resultAllocator;
- bool executePending;
- bool eof;
- };
- // Each call to a MySQL function will use a new MySQLEmbedFunctionContext object
- static __thread ThreadTermFunc threadHookChain;
- static __thread MySQLConnection *cachedConnection = NULL;
- static __thread const char *cachedOptions = NULL;
- static bool cachedConnectionMatches(const char *options)
- {
- return streq(options, cachedOptions);
- }
- static void clearCache()
- {
- ::Release(cachedConnection);
- cachedConnection = NULL;
- free((void *) cachedOptions);
- cachedOptions = NULL;
- }
- static bool mysqlInitialized = false;
- static __thread bool mysqlThreadInitialized = false;
- static CriticalSection initCrit;
- static void terminateMySqlThread()
- {
- clearCache();
- mysql_thread_end();
- mysqlThreadInitialized = false; // In case it was a threadpool thread...
- if (threadHookChain)
- {
- (*threadHookChain)();
- threadHookChain = NULL;
- }
- }
- static void initializeMySqlThread()
- {
- if (!mysqlThreadInitialized)
- {
- {
- CriticalBlock b(initCrit);
- if (!mysqlInitialized)
- {
- mysqlInitialized = true;
- mysql_library_init(0, NULL, NULL);
- }
- }
- mysql_thread_init();
- threadHookChain = addThreadTermFunc(terminateMySqlThread);
- mysqlThreadInitialized = true;
- }
- }
- static void cacheConnection(MySQLConnection *connection, const char *options)
- {
- clearCache();
- cachedOptions = strdup(options);
- cachedConnection = LINK(connection);
- }
- enum MySQLOptionParamType
- {
- ParamTypeNone,
- ParamTypeString,
- ParamTypeUInt,
- ParamTypeULong,
- ParamTypeBool
- };
- struct MySQLOptionDefinition
- {
- const char *name;
- enum mysql_option option;
- MySQLOptionParamType paramType;
- };
- #define addoption(a,b) { #a, a, b }
- MySQLOptionDefinition options[] =
- {
- addoption(MYSQL_OPT_COMPRESS, ParamTypeNone),
- addoption(MYSQL_OPT_CONNECT_TIMEOUT, ParamTypeUInt),
- addoption(MYSQL_OPT_GUESS_CONNECTION, ParamTypeNone),
- addoption(MYSQL_OPT_LOCAL_INFILE, ParamTypeUInt),
- addoption(MYSQL_OPT_NAMED_PIPE, ParamTypeNone),
- addoption(MYSQL_OPT_PROTOCOL, ParamTypeUInt),
- addoption(MYSQL_OPT_READ_TIMEOUT, ParamTypeUInt),
- addoption(MYSQL_OPT_RECONNECT, ParamTypeBool),
- addoption(MYSQL_OPT_SSL_VERIFY_SERVER_CERT, ParamTypeBool),
- addoption(MYSQL_OPT_USE_EMBEDDED_CONNECTION, ParamTypeNone),
- addoption(MYSQL_OPT_USE_REMOTE_CONNECTION, ParamTypeNone),
- addoption(MYSQL_OPT_USE_RESULT, ParamTypeNone),
- addoption(MYSQL_OPT_WRITE_TIMEOUT, ParamTypeUInt),
- addoption(MYSQL_READ_DEFAULT_FILE, ParamTypeString),
- addoption(MYSQL_READ_DEFAULT_GROUP, ParamTypeString),
- addoption(MYSQL_REPORT_DATA_TRUNCATION, ParamTypeBool),
- addoption(MYSQL_SECURE_AUTH, ParamTypeBool),
- addoption(MYSQL_SET_CHARSET_DIR, ParamTypeString),
- addoption(MYSQL_SET_CHARSET_NAME, ParamTypeString),
- addoption(MYSQL_SET_CLIENT_IP, ParamTypeString),
- addoption(MYSQL_SHARED_MEMORY_BASE_NAME, ParamTypeString),
- #if MYSQL_VERSION_ID >= 50507
- addoption(MYSQL_DEFAULT_AUTH, ParamTypeString),
- addoption(MYSQL_PLUGIN_DIR, ParamTypeString),
- #endif
- #if (MYSQL_VERSION_ID >= 50601)
- addoption(MYSQL_OPT_BIND, ParamTypeString),
- #endif
- #if (MYSQL_VERSION_ID >= 50603)
- addoption(MYSQL_OPT_SSL_CA, ParamTypeString),
- addoption(MYSQL_OPT_SSL_CAPATH, ParamTypeString),
- addoption(MYSQL_OPT_SSL_CERT, ParamTypeString),
- addoption(MYSQL_OPT_SSL_CIPHER, ParamTypeString),
- addoption(MYSQL_OPT_SSL_CRL, ParamTypeString),
- addoption(MYSQL_OPT_SSL_CRLPATH, ParamTypeString),
- addoption(MYSQL_OPT_SSL_KEY, ParamTypeString),
- #endif
- #if (MYSQL_VERSION_ID >= 50606)
- addoption(MYSQL_SERVER_PUBLIC_KEY, ParamTypeString),
- #endif
- #if (MYSQL_VERSION_ID >= 50527 && MYSQL_VERSION_ID < 50600) || MYSQL_VERSION_ID >= 50607
- addoption(MYSQL_ENABLE_CLEARTEXT_PLUGIN, ParamTypeBool),
- #endif
- addoption(MYSQL_INIT_COMMAND, ParamTypeString),
- #if (MYSQL_VERSION_ID >= 50610)
- addoption(MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, ParamTypeBool),
- #endif
- #if (MYSQL_VERSION_ID >= 50703)
- addoption(MYSQL_OPT_SSL_ENFORCE, ParamTypeBool),
- #endif
- #if (MYSQL_VERSION_ID >= 50709)
- addoption(MYSQL_OPT_MAX_ALLOWED_PACKET, ParamTypeULong),
- addoption(MYSQL_OPT_NET_BUFFER_LENGTH, ParamTypeULong),
- #endif
- #if (MYSQL_VERSION_ID >= 50710)
- addoption(MYSQL_OPT_TLS_VERSION, ParamTypeString),
- #endif
- #if (MYSQL_VERSION_ID >= 50711)
- addoption(MYSQL_OPT_SSL_MODE, ParamTypeUInt),
- #endif
- { nullptr, (enum mysql_option) 0, ParamTypeNone }
- };
- static MySQLOptionDefinition &lookupOption(const char *optName)
- {
- for (MySQLOptionDefinition *optDef = options; optDef->name != nullptr; optDef++)
- {
- if (stricmp(optName, optDef->name)==0)
- return *optDef;
- }
- failx("Unknown option %s", optName);
- }
- class MySQLEmbedFunctionContext : public CInterfaceOf<IEmbedFunctionContext>
- {
- public:
- MySQLEmbedFunctionContext(const char *options)
- : nextParam(0)
- {
- const char *server = "localhost";
- const char *user = "";
- const char *password = "";
- const char *database = "";
- bool hasMySQLOpt = false;
- bool caching = true;
- unsigned port = 0;
- StringArray opts;
- opts.appendList(options, ",");
- ForEachItemIn(idx, opts)
- {
- const char *opt = opts.item(idx);
- const char *val = strchr(opt, '=');
- if (val)
- {
- StringBuffer optName(val-opt, opt);
- val++;
- if (stricmp(optName, "server")==0)
- server = val; // Note that lifetime of val is adequate for this to be safe
- else if (stricmp(optName, "port")==0)
- port = atoi(val);
- else if (stricmp(optName, "user")==0)
- user = val;
- else if (stricmp(optName, "password")==0)
- password = val;
- else if (stricmp(optName, "database")==0)
- database = val;
- else if (stricmp(optName, "cache")==0)
- caching = clipStrToBool(val);
- else if (strnicmp(optName, "MYSQL_", 6)==0)
- hasMySQLOpt = true;
- else
- failx("Unknown option %s", optName.str());
- }
- }
- initializeMySqlThread();
- if (caching && cachedConnection && cachedConnectionMatches(options))
- {
- conn.set(cachedConnection);
- }
- else
- {
- if (cachedConnection)
- {
- ::Release(cachedConnection);
- cachedConnection = NULL;
- }
- conn.setown(new MySQLConnection(mysql_init(NULL)));
- if (hasMySQLOpt)
- {
- ForEachItemIn(idx, opts)
- {
- const char *opt = opts.item(idx);
- if (strnicmp(opt, "MYSQL_", 6)==0)
- {
- const char *val = strchr(opt, '=');
- StringBuffer optName(opt);
- if (val)
- {
- optName.setLength(val-opt);
- val++;
- }
- MySQLOptionDefinition &optDef = lookupOption(optName);
- int rc;
- if (optDef.paramType == ParamTypeNone)
- {
- if (val)
- failx("Option %s does not take a value", optName.str());
- rc = mysql_options(*conn, optDef.option, nullptr);
- }
- else
- {
- if (!val)
- failx("Option %s requires a value", optName.str());
- switch (optDef.paramType)
- {
- case ParamTypeString:
- rc = mysql_options(*conn, optDef.option, val);
- break;
- case ParamTypeUInt:
- {
- unsigned int oval = strtoul(val, nullptr, 10);
- rc = mysql_options(*conn, optDef.option, (const char *) &oval);
- break;
- }
- case ParamTypeULong:
- {
- unsigned long oval = strtoul(val, nullptr, 10);
- rc = mysql_options(*conn, optDef.option, (const char *) &oval);
- break;
- }
- case ParamTypeBool:
- {
- my_bool oval = clipStrToBool(val);
- rc = mysql_options(*conn, optDef.option, (const char *) &oval);
- break;
- }
- }
- }
- if (rc)
- failx("Failed to set option %s (%s)", optName.str(), mysql_error(*conn));
- }
- }
- }
- if (!mysql_real_connect(*conn, server, user, password, database, port, NULL, 0))
- failx("Failed to connect (%s)", mysql_error(*conn));
- if (caching)
- {
- cacheConnection(conn, options);
- }
- }
- }
- virtual bool getBooleanResult()
- {
- bool ret = mysqlembed::getBooleanResult(NULL, getScalarResult());
- checkSingleRow();
- return ret;
- }
- virtual void getDataResult(size32_t &len, void * &result)
- {
- mysqlembed::getDataResult(NULL, getScalarResult(), len, result);
- checkSingleRow();
- }
- virtual double getRealResult()
- {
- double ret = mysqlembed::getRealResult(NULL, getScalarResult());
- checkSingleRow();
- return ret;
- }
- virtual __int64 getSignedResult()
- {
- __int64 ret = mysqlembed::getSignedResult(NULL, getScalarResult());
- checkSingleRow();
- return ret;
- }
- virtual unsigned __int64 getUnsignedResult()
- {
- unsigned __int64 ret = mysqlembed::getUnsignedResult(NULL, getScalarResult());
- checkSingleRow();
- return ret;
- }
- virtual void getStringResult(size32_t &chars, char * &result)
- {
- mysqlembed::getStringResult(NULL, getScalarResult(), chars, result);
- checkSingleRow();
- }
- virtual void getUTF8Result(size32_t &chars, char * &result)
- {
- mysqlembed::getUTF8Result(NULL, getScalarResult(), chars, result);
- checkSingleRow();
- }
- virtual void getUnicodeResult(size32_t &chars, UChar * &result)
- {
- mysqlembed::getUnicodeResult(NULL, getScalarResult(), chars, result);
- checkSingleRow();
- }
- virtual void getDecimalResult(Decimal &value)
- {
- mysqlembed::getDecimalResult(NULL, getScalarResult(), value);
- checkSingleRow();
- }
- virtual void getSetResult(bool & __isAllResult, size32_t & __resultBytes, void * & __result, int elemType, size32_t elemSize)
- {
- UNSUPPORTED("SET results");
- }
- virtual IRowStream *getDatasetResult(IEngineRowAllocator * _resultAllocator)
- {
- return new MySQLRowStream(inputStream, stmtInfo, _resultAllocator);
- }
- virtual byte * getRowResult(IEngineRowAllocator * _resultAllocator)
- {
- if (!stmtInfo->hasResult())
- typeError("row", NULL);
- lazyExecute();
- MySQLRowStream stream(NULL, stmtInfo, _resultAllocator);
- roxiemem::OwnedConstRoxieRow ret = stream.nextRow();
- roxiemem::OwnedConstRoxieRow ret2 = stream.nextRow();
- stream.stop();
- if (ret == NULL || ret2 != NULL) // Check for exactly one returned row
- typeError("row", NULL);
- return (byte *) ret.getClear();
- }
- virtual size32_t getTransformResult(ARowBuilder & rowBuilder)
- {
- lazyExecute();
- if (!stmtInfo->next())
- typeError("row", NULL);
- MySQLRowBuilder mysqlRowBuilder(stmtInfo->queryResultBindings());
- const RtlTypeInfo *typeInfo = rowBuilder.queryAllocator()->queryOutputMeta()->queryTypeInfo();
- assertex(typeInfo);
- RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
- size32_t ret = typeInfo->build(rowBuilder, 0, &dummyField, mysqlRowBuilder);
- if (stmtInfo->next())
- typeError("row", NULL); // Check that a single row was returned
- return ret;
- }
- virtual void bindRowParam(const char *name, IOutputMetaData & metaVal, byte *val)
- {
- MySQLRecordBinder binder(metaVal.queryTypeInfo(), stmtInfo->queryInputBindings(), nextParam);
- binder.processRow(val);
- nextParam += binder.numFields();
- }
- virtual void bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val)
- {
- // We only support a single dataset parameter...
- if (inputStream)
- {
- fail("At most one dataset parameter supported");
- }
- inputStream.setown(new MySQLDatasetBinder(LINK(val), metaVal.queryTypeInfo(), stmtInfo->queryInputBindings(), nextParam));
- nextParam += inputStream->numFields();
- }
- virtual void bindBooleanParam(const char *name, bool val)
- {
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_TINY, sizeof(val));
- * (bool *) bindInfo.buffer = val;
- bindInfo.is_unsigned = true;
- }
- virtual void bindDataParam(const char *name, size32_t len, const void *val)
- {
- size32_t bytes;
- void *data;
- rtlStrToDataX(bytes, data, len, val);
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_BLOB, 0);
- bindInfo.buffer = data;
- bindInfo.buffer_length = bytes;
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void bindFloatParam(const char *name, float val)
- {
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_FLOAT, sizeof(val));
- * (float *) bindInfo.buffer = val;
- }
- virtual void bindRealParam(const char *name, double val)
- {
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_DOUBLE, sizeof(val));
- * (double *) bindInfo.buffer = val;
- }
- virtual void bindSignedSizeParam(const char *name, int size, __int64 val)
- {
- bindSignedParam(name, val);
- }
- virtual void bindSignedParam(const char *name, __int64 val)
- {
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_LONGLONG, sizeof(val));
- * (__int64 *) bindInfo.buffer = val;
- bindInfo.is_unsigned = false;
- }
- virtual void bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val)
- {
- bindUnsignedParam(name, val);
- }
- virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
- {
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_LONGLONG, sizeof(val));
- * (unsigned __int64 *) bindInfo.buffer = val;
- bindInfo.is_unsigned = true;
- }
- virtual void bindStringParam(const char *name, size32_t len, const char *val)
- {
- size32_t utf8chars;
- char *utf8;
- rtlStrToUtf8X(utf8chars, utf8, len, val);
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = utf8;
- bindInfo.buffer_length = rtlUtf8Size(utf8chars, utf8);
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void bindVStringParam(const char *name, const char *val)
- {
- bindStringParam(name, strlen(val), val);
- }
- virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
- {
- size32_t utf8chars;
- char *utf8;
- rtlUtf8ToUtf8X(utf8chars, utf8, chars, val);
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = utf8;
- bindInfo.buffer_length = rtlUtf8Size(utf8chars, utf8);
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
- {
- size32_t utf8chars;
- char *utf8;
- rtlUnicodeToUtf8X(utf8chars, utf8, chars, val);
- MYSQL_BIND &bindInfo = findParameter(name, MYSQL_TYPE_STRING, 0);
- bindInfo.buffer = utf8;
- bindInfo.buffer_length = rtlUtf8Size(utf8chars, utf8);
- bindInfo.length = &bindInfo.buffer_length;
- }
- virtual void bindSetParam(const char *name, int elemType, size32_t elemSize, bool isAll, size32_t totalBytes, const void *setData)
- {
- UNSUPPORTED("SET parameters"); // MySQL does support sets, so MIGHT be possible...
- }
- virtual IInterface *bindParamWriter(IInterface *esdl, const char *esdlservice, const char *esdltype, const char *name)
- {
- return NULL;
- }
- virtual void paramWriterCommit(IInterface *writer)
- {
- }
- virtual void writeResult(IInterface *esdl, const char *esdlservice, const char *esdltype, IInterface *writer)
- {
- }
- virtual void importFunction(size32_t lenChars, const char *text)
- {
- throwUnexpected();
- }
- virtual void compileEmbeddedScript(size32_t chars, const char *script)
- {
- size32_t len = rtlUtf8Size(chars, script);
- Owned<MySQLStatement> stmt = new MySQLStatement(mysql_stmt_init(*conn));
- if (!*stmt)
- fail("failed to create statement");
- if (mysql_stmt_prepare(*stmt, script, len))
- fail(mysql_stmt_error(*stmt));
- stmtInfo.setown(new MySQLPreparedStatement(conn, stmt));
- }
- virtual void callFunction()
- {
- if (nextParam != stmtInfo->queryInputBindings().numColumns())
- failx("Not enough parameters supplied (%d parameters supplied, but statement has %d bound columns)", nextParam, stmtInfo->queryInputBindings().numColumns());
- // We actually do the execute later, when the result is fetched
- }
- protected:
- void lazyExecute()
- {
- if (inputStream)
- inputStream->executeAll(stmtInfo);
- else
- stmtInfo->execute();
- }
- const MYSQL_BIND &getScalarResult()
- {
- if (!stmtInfo->hasResult() || stmtInfo->queryResultBindings().numColumns() != 1)
- typeError("scalar", NULL);
- lazyExecute();
- if (!stmtInfo->next())
- typeError("scalar", NULL);
- return stmtInfo->queryResultBindings().queryColumn(0, NULL);
- }
- void checkSingleRow()
- {
- if (stmtInfo->next())
- typeError("scalar", NULL);
- }
- inline MYSQL_BIND &findParameter(const char *name, enum_field_types sqlType, unsigned size)
- {
- // Everything is positional in MySQL
- MYSQL_BIND &bindInfo = stmtInfo->queryInputBindings().queryColumn(nextParam++, name);
- createBindBuffer(bindInfo, sqlType, size);
- return bindInfo;
- }
- Owned<MySQLConnection> conn;
- Owned<MySQLPreparedStatement> stmtInfo;
- Owned<MySQLDatasetBinder> inputStream;
- int nextParam;
- };
- class MySQLEmbedContext : public CInterfaceOf<IEmbedContext>
- {
- public:
- virtual IEmbedFunctionContext *createFunctionContext(unsigned flags, const char *options)
- {
- return createFunctionContextEx(NULL, flags, options);
- }
- virtual IEmbedFunctionContext *createFunctionContextEx(ICodeContext * ctx, unsigned flags, const char *options)
- {
- if (flags & EFimport)
- UNSUPPORTED("IMPORT");
- else
- return new MySQLEmbedFunctionContext(options);
- }
- virtual IEmbedServiceContext *createServiceContext(const char *service, unsigned flags, const char *options)
- {
- throwUnexpected();
- }
- };
- extern IEmbedContext* getEmbedContext()
- {
- return new MySQLEmbedContext();
- }
- extern bool syntaxCheck(const char *script)
- {
- return true; // MORE
- }
- } // namespace
|