mysqlconn.inc 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. {$IFDEF MYSQL56_UP}
  2. {$DEFINE MYSQL55_UP}
  3. {$ENDIF}
  4. {$IFDEF MYSQL55_UP}
  5. {$DEFINE MYSQL51_UP}
  6. {$ENDIF}
  7. {$IFDEF MYSQL51_UP}
  8. {$DEFINE MYSQL50_UP}
  9. {$ENDIF}
  10. {$mode objfpc}{$H+}
  11. interface
  12. uses
  13. Classes, SysUtils,bufdataset,sqldb,db,ctypes,
  14. {$IFDEF mysql56}
  15. mysql56dyn;
  16. {$ELSE}
  17. {$IFDEF mysql55}
  18. mysql55dyn;
  19. {$ELSE}
  20. {$IFDEF mysql51}
  21. mysql51dyn;
  22. {$ELSE}
  23. {$IfDef mysql50}
  24. mysql50dyn;
  25. {$ELSE}
  26. {$IfDef mysql41}
  27. mysql41dyn;
  28. {$ELSE}
  29. mysql40dyn;
  30. {$EndIf}
  31. {$EndIf}
  32. {$endif}
  33. {$endif}
  34. {$ENDIF}
  35. Const
  36. MySQLVersion =
  37. {$IFDEF mysql56}
  38. '5.6';
  39. {$ELSE}
  40. {$IFDEF mysql55}
  41. '5.5';
  42. {$ELSE}
  43. {$IFDEF mysql51}
  44. '5.1';
  45. {$else}
  46. {$IfDef mysql50}
  47. '5.0';
  48. {$ELSE}
  49. {$IfDef mysql41}
  50. '4.1';
  51. {$ELSE}
  52. '4.0';
  53. {$EndIf}
  54. {$EndIf}
  55. {$endif}
  56. {$endif}
  57. {$ENDIF}
  58. MariaDBVersion =
  59. {$IFDEF mysql56} // MariaDB 10.0 is compatible with MySQL 5.6
  60. '10.0';
  61. {$ELSE} // MariaDB 5.1..5.5 presumably report the same version number as MySQL
  62. MySQLVersion;
  63. {$ENDIF}
  64. Type
  65. TTransactionName = Class(TSQLHandle)
  66. protected
  67. end;
  68. { TCursorName }
  69. TCursorName = Class(TSQLCursor)
  70. protected
  71. FRes: PMYSQL_RES; { Record pointer }
  72. FStatement : String;
  73. Row : MYSQL_ROW;
  74. Lengths : pculong; { Lengths of the columns of the current row }
  75. RowsAffected : QWord;
  76. LastInsertID : QWord;
  77. ParamBinding : TParamBinding;
  78. ParamReplaceString : String;
  79. MapDSRowToMSQLRow : array of integer;
  80. end;
  81. { TConnectionName }
  82. TConnectionName = class (TSQLConnection)
  83. private
  84. FHostInfo: String;
  85. FServerInfo: String;
  86. FMySQL : PMySQL;
  87. function GetClientInfo: string;
  88. function GetServerStatus: String;
  89. procedure ConnectMySQL(var HMySQL: PMySQL);
  90. procedure ExecuteDirectMySQL(const query : string);
  91. function EscapeString(const Str : string) : string;
  92. protected
  93. Procedure ConnectToServer; virtual;
  94. Procedure SelectDatabase; virtual;
  95. function MySQLDataType(AField: PMYSQL_FIELD; var NewType: TFieldType; var NewSize: Integer): Boolean;
  96. function MySQLWriteData(AField: PMYSQL_FIELD; FieldDef: TFieldDef; Source, Dest: PChar; Len: integer; out CreateBlob : boolean): Boolean;
  97. // SQLConnection methods
  98. procedure DoInternalConnect; override;
  99. procedure DoInternalDisconnect; override;
  100. function GetHandle : pointer; override;
  101. function GetAsSQLText(Field : TField) : string; overload; override;
  102. function GetAsSQLText(Param : TParam) : string; overload; override;
  103. Function AllocateCursorHandle : TSQLCursor; override;
  104. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  105. Function AllocateTransactionHandle : TSQLHandle; override;
  106. function StrToStatementType(s : string) : TStatementType; override;
  107. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  108. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  109. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  110. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams); override;
  111. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  112. function Fetch(cursor : TSQLCursor) : boolean; override;
  113. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  114. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor;ATransaction : TSQLTransaction); override;
  115. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  116. function Commit(trans : TSQLHandle) : boolean; override;
  117. function RollBack(trans : TSQLHandle) : boolean; override;
  118. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  119. procedure CommitRetaining(trans : TSQLHandle); override;
  120. procedure RollBackRetaining(trans : TSQLHandle); override;
  121. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  122. procedure UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string); override;
  123. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  124. function RefreshLastInsertID(Query : TCustomSQLQuery; Field : TField): Boolean; override;
  125. Public
  126. constructor Create(AOwner : TComponent); override;
  127. procedure GetFieldNames(const TableName : string; List : TStrings); override;
  128. procedure GetTableNames(List : TStrings; SystemTables : Boolean = false); override;
  129. function GetConnectionInfo(InfoType:TConnInfoType): string; override;
  130. Function GetInsertID: int64;
  131. procedure CreateDB; override;
  132. procedure DropDB; override;
  133. Property ServerInfo : String Read FServerInfo;
  134. Property HostInfo : String Read FHostInfo;
  135. property ClientInfo: string read GetClientInfo;
  136. property ServerStatus : String read GetServerStatus;
  137. published
  138. property DatabaseName;
  139. property HostName;
  140. property KeepConnection;
  141. property LoginPrompt;
  142. property Params;
  143. property Port stored false;
  144. property OnLogin;
  145. end;
  146. { TMySQLConnectionDef }
  147. TMySQLConnectionDef = Class(TConnectionDef)
  148. Class Function TypeName : String; override;
  149. Class Function ConnectionClass : TSQLConnectionClass; override;
  150. Class Function Description : String; override;
  151. Class Function DefaultLibraryName : String; override;
  152. Class Function LoadFunction : TLibraryLoadFunction; override;
  153. Class Function UnLoadFunction : TLibraryUnLoadFunction; override;
  154. Class Function LoadedLibraryName : string; override;
  155. end;
  156. {$IFDEF mysql56}
  157. TMySQL56Connection = Class(TConnectionName);
  158. TMySQL56ConnectionDef = Class(TMySQLConnectionDef);
  159. TMySQL56Transaction = Class(TTransactionName);
  160. TMySQL56Cursor = Class(TCursorName);
  161. {$ELSE}
  162. {$ifdef mysql55}
  163. TMySQL55Connection = Class(TConnectionName);
  164. TMySQL55ConnectionDef = Class(TMySQLConnectionDef);
  165. TMySQL55Transaction = Class(TTransactionName);
  166. TMySQL55Cursor = Class(TCursorName);
  167. {$else}
  168. {$IfDef mysql51}
  169. TMySQL51Connection = Class(TConnectionName);
  170. TMySQL51ConnectionDef = Class(TMySQLConnectionDef);
  171. TMySQL51Transaction = Class(TTransactionName);
  172. TMySQL51Cursor = Class(TCursorName);
  173. {$ELSE}
  174. {$IfDef mysql50}
  175. TMySQL50Connection = Class(TConnectionName);
  176. TMySQL50ConnectionDef = Class(TMySQLConnectionDef);
  177. TMySQL50Transaction = Class(TTransactionName);
  178. TMySQL50Cursor = Class(TCursorName);
  179. {$ELSE}
  180. {$IfDef mysql41}
  181. TMySQL41Connection = Class(TConnectionName);
  182. TMySQL41ConnectionDef = Class(TMySQLConnectionDef);
  183. TMySQL41Transaction = Class(TTransactionName);
  184. TMySQL41Cursor = Class(TCursorName);
  185. {$ELSE}
  186. TMySQL40Connection = Class(TConnectionName);
  187. TMySQL40ConnectionDef = Class(TMySQLConnectionDef);
  188. TMySQL40Transaction = Class(TTransactionName);
  189. TMySQL40Cursor = Class(TCursorName);
  190. {$EndIf}
  191. {$endif}
  192. {$EndIf}
  193. {$ENDIF}
  194. {$ENDIF}
  195. implementation
  196. uses
  197. dbconst,
  198. strutils,
  199. dateutils,
  200. FmtBCD;
  201. const
  202. Mysql_Option_Names : array[mysql_option] of string = ('MYSQL_OPT_CONNECT_TIMEOUT','MYSQL_OPT_COMPRESS',
  203. 'MYSQL_OPT_NAMED_PIPE','MYSQL_INIT_COMMAND',
  204. 'MYSQL_READ_DEFAULT_FILE','MYSQL_READ_DEFAULT_GROUP',
  205. 'MYSQL_SET_CHARSET_DIR','MYSQL_SET_CHARSET_NAME',
  206. 'MYSQL_OPT_LOCAL_INFILE','MYSQL_OPT_PROTOCOL',
  207. 'MYSQL_SHARED_MEMORY_BASE_NAME','MYSQL_OPT_READ_TIMEOUT',
  208. 'MYSQL_OPT_WRITE_TIMEOUT','MYSQL_OPT_USE_RESULT',
  209. 'MYSQL_OPT_USE_REMOTE_CONNECTION','MYSQL_OPT_USE_EMBEDDED_CONNECTION',
  210. 'MYSQL_OPT_GUESS_CONNECTION','MYSQL_SET_CLIENT_IP',
  211. 'MYSQL_SECURE_AUTH'
  212. {$IFDEF MYSQL50_UP}
  213. ,'MYSQL_REPORT_DATA_TRUNCATION', 'MYSQL_OPT_RECONNECT'
  214. {$IFDEF mysql51_UP}
  215. ,'MYSQL_OPT_SSL_VERIFY_SERVER_CERT'
  216. {$IFDEF mysql55_UP}
  217. ,'MYSQL_PLUGIN_DIR', 'MYSQL_DEFAULT_AUTH'
  218. {$IFDEF MYSQL56_UP}
  219. ,'MYSQL_OPT_BIND'
  220. ,'MYSQL_OPT_SSL_KEY', 'MYSQL_OPT_SSL_CERT', 'MYSQL_OPT_SSL_CA', 'MYSQL_OPT_SSL_CAPATH', 'MYSQL_OPT_SSL_CIPHER', 'MYSQL_OPT_SSL_CRL', 'MYSQL_OPT_SSL_CRLPATH'
  221. ,'MYSQL_OPT_CONNECT_ATTR_RESET', 'MYSQL_OPT_CONNECT_ATTR_ADD', 'MYSQL_OPT_CONNECT_ATTR_DELETE'
  222. ,'MYSQL_SERVER_PUBLIC_KEY'
  223. ,'MYSQL_ENABLE_CLEARTEXT_PLUGIN'
  224. ,'MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS'
  225. {$ENDIF}
  226. {$ENDIF}
  227. {$ENDIF}
  228. {$ENDIF}
  229. );
  230. Resourcestring
  231. SErrServerConnectFailed = 'Server connect failed.';
  232. SErrSetCharsetFailed = 'Failed to set connection character set: %s';
  233. SErrDatabaseSelectFailed = 'Failed to select database: %s';
  234. SErrDatabaseCreate = 'Failed to create database: %s';
  235. SErrDatabaseDrop = 'Failed to drop database: %s';
  236. SErrNoData = 'No data for record';
  237. SErrExecuting = 'Error executing query: %s';
  238. SErrFetchingdata = 'Error fetching row data: %s';
  239. SErrGettingResult = 'Error getting result set: %s';
  240. SErrNoQueryResult = 'No result from query.';
  241. SErrVersionMismatch = '%s can not work with the installed MySQL client version: Expected (%s), got (%s).';
  242. SErrSettingParameter = 'Error setting parameter "%s"';
  243. Procedure MySQLError(R : PMySQL; Msg: String; Comp : TComponent);
  244. Var
  245. MySQLError, MySQLState : String;
  246. MySQLErrno: integer;
  247. begin
  248. If (R<>Nil) then
  249. begin
  250. MySQLError:=StrPas(mysql_error(R));
  251. MySQLErrno:=mysql_errno(R);
  252. MySQLState:=StrPas(mysql_sqlstate(R));
  253. end
  254. else
  255. begin
  256. MySQLError:='';
  257. MySQLErrno:=0;
  258. MySQLState:='';
  259. end;
  260. raise ESQLDatabaseError.CreateFmt(Msg, [MySQLError], Comp, MySQLErrno, MySQLState);
  261. end;
  262. function MysqlOption(const OptionName: string; out AMysql_Option: mysql_option) : boolean;
  263. var AMysql_Option_i: mysql_option;
  264. begin
  265. result := false;
  266. for AMysql_Option_i:=low(AMysql_Option) to high(AMysql_Option) do
  267. if sametext(Mysql_Option_Names[AMysql_Option_i],OptionName) then
  268. begin
  269. result := true;
  270. AMysql_Option:=AMysql_Option_i;
  271. break;
  272. end;
  273. end;
  274. { TConnectionName }
  275. function TConnectionName.StrToStatementType(s : string) : TStatementType;
  276. begin
  277. s:=Lowercase(s);
  278. if (s='analyze') or (s='check') or (s='checksum') or (s='optimize') or (s='repair') or (s='show') then
  279. exit(stSelect)
  280. else if s='call' then
  281. exit(stExecProcedure)
  282. else
  283. Result := inherited StrToStatementType(s);
  284. end;
  285. function TConnectionName.GetClientInfo: string;
  286. begin
  287. // To make it possible to call this if there's no connection yet
  288. InitialiseMysql;
  289. Try
  290. Result:=strpas(mysql_get_client_info());
  291. Finally
  292. ReleaseMysql;
  293. end;
  294. end;
  295. function TConnectionName.GetServerStatus: String;
  296. begin
  297. CheckConnected;
  298. Result := mysql_stat(FMYSQL);
  299. end;
  300. Function TConnectionName.GetInsertID: int64;
  301. begin
  302. CheckConnected;
  303. Result:=mysql_insert_id(GetHandle);
  304. end;
  305. procedure TConnectionName.ConnectMySQL(var HMySQL: PMySQL);
  306. Var
  307. APort : Cardinal;
  308. i,e: integer;
  309. AMysql_Option: mysql_option;
  310. OptStr: string;
  311. OptInt: cuint;
  312. Opt: pointer;
  313. begin
  314. HMySQL := mysql_init(HMySQL);
  315. APort:=Abs(StrToIntDef(Params.Values['Port'],0));
  316. for i := 0 to Params.Count-1 do
  317. begin
  318. if MysqlOption(Params.Names[i],AMysql_Option) then
  319. begin
  320. OptStr:=Params.ValueFromIndex[i];
  321. val(OptStr,OptInt,e);
  322. if e=0 then
  323. Opt := @OptInt
  324. else
  325. Opt := pchar(OptStr);
  326. if mysql_options(HMySQL,AMysql_Option,Opt) <> 0 then
  327. MySQLError(HMySQL,Format(SErrSettingParameter,[Params.Names[i]]),Self);
  328. end;
  329. end;
  330. HMySQL:=mysql_real_connect(HMySQL,PChar(HostName),PChar(UserName),PChar(Password),Nil,APort,Nil,CLIENT_MULTI_RESULTS); //CLIENT_MULTI_RESULTS is required by CALL SQL statement(executes stored procedure), that produces result sets
  331. If (HMySQL=Nil) then
  332. MySQLError(Nil,SErrServerConnectFailed,Self);
  333. if (trim(CharSet) <> '') then
  334. // major_version*10000 + minor_version *100 + sub_version
  335. if (50007 <= mysql_get_server_version(HMySQL)) then
  336. begin
  337. // Only available for MySQL 5.0.7 and later...
  338. if mysql_set_character_set(HMySQL, PChar(CharSet)) <> 0 then
  339. MySQLError(HMySQL,SErrSetCharsetFailed,Self);
  340. end
  341. else
  342. if mysql_query(HMySQL,PChar('SET NAMES ''' + EscapeString(CharSet) +'''')) <> 0 then
  343. MySQLError(HMySQL,SErrExecuting,Self);
  344. end;
  345. function TConnectionName.GetAsSQLText(Field : TField) : string;
  346. begin
  347. if (not assigned(Field)) or Field.IsNull then
  348. Result := 'Null'
  349. else if Field.DataType = ftString then
  350. Result := '''' + EscapeString(Field.AsString) + ''''
  351. else
  352. Result := inherited GetAsSqlText(Field);
  353. end;
  354. function TConnectionName.GetAsSQLText(Param: TParam) : string;
  355. begin
  356. if (not assigned(Param)) or Param.IsNull then
  357. Result := 'Null'
  358. else if Param.DataType in [ftString,ftFixedChar,ftBlob,ftMemo,ftBytes,ftVarBytes] then
  359. Result := '''' + EscapeString(Param.AsString) + ''''
  360. else
  361. Result := inherited GetAsSqlText(Param);
  362. end;
  363. Procedure TConnectionName.ConnectToServer;
  364. begin
  365. ConnectMySQL(FMySQL);
  366. FServerInfo := strpas(mysql_get_server_info(FMYSQL));
  367. FHostInfo := strpas(mysql_get_host_info(FMYSQL));
  368. end;
  369. Procedure TConnectionName.SelectDatabase;
  370. begin
  371. if mysql_select_db(FMySQL,pchar(DatabaseName))<>0 then
  372. MySQLError(FMySQL,SErrDatabaseSelectFailed,Self);
  373. end;
  374. procedure TConnectionName.CreateDB;
  375. begin
  376. ExecuteDirectMySQL('CREATE DATABASE ' +DatabaseName);
  377. end;
  378. procedure TConnectionName.DropDB;
  379. begin
  380. ExecuteDirectMySQL('DROP DATABASE ' +DatabaseName);
  381. end;
  382. procedure TConnectionName.ExecuteDirectMySQL(const query : string);
  383. var AMySQL : PMySQL;
  384. begin
  385. CheckDisConnected;
  386. InitialiseMysql;
  387. try
  388. AMySQL := nil;
  389. ConnectMySQL(AMySQL);
  390. try
  391. if mysql_query(AMySQL,pchar(query))<>0 then
  392. MySQLError(AMySQL,SErrExecuting,Self);
  393. finally
  394. mysql_close(AMySQL);
  395. end;
  396. finally
  397. ReleaseMysql;
  398. end;
  399. end;
  400. function TConnectionName.EscapeString(const Str: string): string;
  401. var Len : integer;
  402. begin
  403. SetLength(result,length(str)*2+1);
  404. Len := mysql_real_escape_string(FMySQL,pchar(Result),pchar(Str),length(Str));
  405. SetLength(result,Len);
  406. end;
  407. procedure TConnectionName.DoInternalConnect;
  408. var
  409. FullVersion: string;
  410. begin
  411. InitialiseMysql;
  412. Fullversion:=strpas(mysql_get_client_info());
  413. // Version string should start with version number:
  414. // Note: in case of MariaDB version mismatch: tough luck, we report MySQL
  415. // version only.
  416. if (pos(MySQLVersion, Fullversion) <> 1) and
  417. (pos(MariaDBVersion, Fullversion) <> 1) then
  418. Raise EInOutError.CreateFmt(SErrVersionMisMatch,[ClassName,MySQLVersion,FullVersion]);
  419. inherited DoInternalConnect;
  420. ConnectToServer;
  421. SelectDatabase;
  422. end;
  423. procedure TConnectionName.DoInternalDisconnect;
  424. begin
  425. inherited DoInternalDisconnect;
  426. mysql_close(FMySQL);
  427. FMySQL:=Nil;
  428. ReleaseMysql;
  429. end;
  430. function TConnectionName.GetHandle: pointer;
  431. begin
  432. Result:=FMySQL;
  433. end;
  434. Function TConnectionName.AllocateCursorHandle: TSQLCursor;
  435. begin
  436. {$IFDEF mysql56}
  437. Result:=TMySQL56Cursor.Create;
  438. {$ELSE}
  439. {$IfDef mysql55}
  440. Result:=TMySQL55Cursor.Create;
  441. {$ELSE}
  442. {$IfDef mysql51}
  443. Result:=TMySQL51Cursor.Create;
  444. {$ELSE}
  445. {$IfDef mysql50}
  446. Result:=TMySQL50Cursor.Create;
  447. {$ELSE}
  448. {$IfDef mysql41}
  449. Result:=TMySQL41Cursor.Create;
  450. {$ELSE}
  451. Result:=TMySQL40Cursor.Create;
  452. {$EndIf}
  453. {$EndIf}
  454. {$EndIf}
  455. {$EndIf}
  456. {$ENDIF}
  457. end;
  458. Procedure TConnectionName.DeAllocateCursorHandle(var cursor : TSQLCursor);
  459. begin
  460. FreeAndNil(cursor);
  461. end;
  462. Function TConnectionName.AllocateTransactionHandle: TSQLHandle;
  463. begin
  464. // Result:=TTransactionName.Create;
  465. Result := nil;
  466. end;
  467. procedure TConnectionName.PrepareStatement(cursor: TSQLCursor;
  468. ATransaction: TSQLTransaction; buf: string;AParams : TParams);
  469. begin
  470. // if assigned(AParams) and (AParams.count > 0) then
  471. // DatabaseError('Parameters (not) yet supported for the MySQL SqlDB connection.',self);
  472. With Cursor as TCursorName do
  473. begin
  474. FStatement:=Buf;
  475. if assigned(AParams) and (AParams.count > 0) then
  476. FStatement := AParams.ParseSQL(FStatement,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psSimulated,paramBinding,ParamReplaceString);
  477. end
  478. end;
  479. procedure TConnectionName.UnPrepareStatement(cursor: TSQLCursor);
  480. Var
  481. C : TCursorName;
  482. begin
  483. C:=Cursor as TCursorName;
  484. if assigned(C.FRes) then //ExecSQL with dataset returned
  485. begin
  486. mysql_free_result(C.FRes);
  487. C.FRes:=nil;
  488. end;
  489. end;
  490. procedure TConnectionName.FreeFldBuffers(cursor: TSQLCursor);
  491. Var
  492. C : TCursorName;
  493. begin
  494. C:=Cursor as TCursorName;
  495. if assigned(C.FRes) then
  496. begin
  497. mysql_free_result(C.FRes);
  498. C.FRes:=Nil;
  499. end;
  500. SetLength(c.MapDSRowToMSQLRow,0);
  501. inherited;
  502. end;
  503. procedure TConnectionName.Execute(cursor: TSQLCursor;
  504. atransaction: tSQLtransaction;AParams : TParams);
  505. Var
  506. C : TCursorName;
  507. i : integer;
  508. ParamNames,ParamValues : array of string;
  509. Res: PMYSQL_RES;
  510. begin
  511. C:=Cursor as TCursorName;
  512. If (C.FRes=Nil) then
  513. begin
  514. if Assigned(AParams) and (AParams.count > 0) then
  515. begin
  516. setlength(ParamNames,AParams.Count);
  517. setlength(ParamValues,AParams.Count);
  518. for i := 0 to AParams.count -1 do
  519. begin
  520. ParamNames[AParams.count-i-1] := C.ParamReplaceString+inttostr(AParams[i].Index+1);
  521. ParamValues[AParams.count-i-1] := GetAsSQLText(AParams[i]);
  522. end;
  523. // paramreplacestring kan een probleem geven bij postgres als hij niet meer gewoon $ is?
  524. C.FStatement := stringsreplace(C.FStatement,ParamNames,ParamValues,[rfReplaceAll]);
  525. end;
  526. Log(detExecute, C.FStatement);
  527. if mysql_query(FMySQL,Pchar(C.FStatement))<>0 then
  528. begin
  529. if not ForcedClose then
  530. MySQLError(FMYSQL,SErrExecuting,Self)
  531. else //don't return a resulset. We are shutting down, not opening.
  532. begin
  533. C.RowsAffected:=0;
  534. C.FSelectable:= False;
  535. C.FRes:=nil;
  536. end;
  537. end
  538. else
  539. begin
  540. C.RowsAffected := mysql_affected_rows(FMYSQL);
  541. C.LastInsertID := mysql_insert_id(FMYSQL);
  542. C.FSelectable := False;
  543. repeat
  544. Res:=mysql_store_result(FMySQL); //returns a null pointer also if the statement didn't return a result set
  545. if mysql_errno(FMySQL)<>0 then
  546. begin
  547. if not ForcedClose then
  548. MySQLError(FMySQL, SErrGettingResult, Self)
  549. else
  550. begin
  551. C.RowsAffected:=0;
  552. C.FSelectable:= False;
  553. C.FRes:=nil;
  554. break;
  555. end;
  556. end;
  557. if Res<>nil then
  558. begin
  559. mysql_free_result(C.FRes);
  560. C.FRes:=Res;
  561. C.FSelectable:=True;
  562. end;
  563. until mysql_next_result(FMySQL)<>0;
  564. end;
  565. end;
  566. end;
  567. function TConnectionName.MySQLDataType(AField: PMYSQL_FIELD; var NewType: TFieldType; var NewSize: Integer): Boolean;
  568. var ASize, ADecimals: integer;
  569. begin
  570. Result := True;
  571. ASize := AField^.length;
  572. NewSize := 0;
  573. case AField^.ftype of
  574. FIELD_TYPE_LONGLONG:
  575. begin
  576. NewType := ftLargeint;
  577. end;
  578. FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_YEAR:
  579. begin
  580. if AField^.flags and UNSIGNED_FLAG <> 0 then
  581. NewType := ftWord
  582. else
  583. NewType := ftSmallint;
  584. end;
  585. FIELD_TYPE_LONG, FIELD_TYPE_INT24:
  586. begin
  587. if AField^.flags and AUTO_INCREMENT_FLAG <> 0 then
  588. NewType := ftAutoInc
  589. else
  590. NewType := ftInteger;
  591. end;
  592. {$ifdef mysql50_up}
  593. FIELD_TYPE_NEWDECIMAL,
  594. {$endif}
  595. FIELD_TYPE_DECIMAL:
  596. begin
  597. ADecimals:=AField^.decimals;
  598. if (ADecimals < 5) and (ASize-2-ADecimals < 15) then //ASize is display size i.e. with sign and decimal point
  599. NewType := ftBCD
  600. else if (ADecimals = 0) and (ASize < 20) then
  601. NewType := ftLargeInt
  602. else
  603. NewType := ftFmtBCD;
  604. NewSize := ADecimals;
  605. end;
  606. FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  607. begin
  608. NewType := ftFloat;
  609. end;
  610. FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  611. begin
  612. NewType := ftDateTime;
  613. end;
  614. FIELD_TYPE_DATE:
  615. begin
  616. NewType := ftDate;
  617. end;
  618. FIELD_TYPE_TIME:
  619. begin
  620. NewType := ftTime;
  621. end;
  622. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  623. begin
  624. // Since mysql server version 5.0.3 string-fields with a length of more
  625. // then 256 characters are suported
  626. if AField^.ftype = FIELD_TYPE_STRING then
  627. NewType := ftFixedChar
  628. else
  629. NewType := ftString;
  630. {$IFDEF MYSQL50_UP}
  631. if AField^.charsetnr = 63 then //BINARY vs. CHAR, VARBINARY vs. VARCHAR
  632. if NewType = ftFixedChar then
  633. NewType := ftBytes
  634. else
  635. NewType := ftVarBytes;
  636. {$ENDIF}
  637. NewSize := ASize;
  638. end;
  639. FIELD_TYPE_TINY_BLOB..FIELD_TYPE_BLOB:
  640. begin
  641. {$IFDEF MYSQL50_UP}
  642. if AField^.charsetnr = 63 then //character set is binary
  643. NewType := ftBlob
  644. else
  645. NewType := ftMemo;
  646. {$ELSE}
  647. NewType := ftBlob;
  648. {$ENDIF}
  649. end;
  650. {$IFDEF MYSQL50_UP}
  651. FIELD_TYPE_BIT:
  652. NewType := ftLargeInt;
  653. {$ENDIF}
  654. else
  655. Result := False;
  656. end;
  657. end;
  658. procedure TConnectionName.AddFieldDefs(cursor: TSQLCursor;
  659. FieldDefs: TfieldDefs);
  660. var
  661. C : TCursorName;
  662. I, TF, FC: Integer;
  663. field: PMYSQL_FIELD;
  664. DFT: TFieldType;
  665. DFS: Integer;
  666. begin
  667. // Writeln('MySQL: Adding fielddefs');
  668. C:=(Cursor as TCursorName);
  669. If (C.FRes=Nil) then
  670. begin
  671. // Writeln('res is nil');
  672. MySQLError(FMySQL,SErrNoQueryResult,Self);
  673. end;
  674. // Writeln('MySQL: have result');
  675. FC:=mysql_num_fields(C.FRes);
  676. SetLength(c.MapDSRowToMSQLRow,FC);
  677. TF := 1;
  678. For I:= 0 to FC-1 do
  679. begin
  680. field := mysql_fetch_field_direct(C.FRES, I);
  681. // Writeln('MySQL: creating fielddef ',I+1);
  682. if MySQLDataType(field, DFT, DFS) then
  683. begin
  684. FieldDefs.Add(FieldDefs.MakeNameUnique(field^.name), DFT, DFS,
  685. (field^.flags and (AUTO_INCREMENT_FLAG or NOT_NULL_FLAG {$IFDEF MYSQL50_UP}or NO_DEFAULT_VALUE_FLAG{$ENDIF})) = (NOT_NULL_FLAG {$IFDEF MYSQL50_UP}or NO_DEFAULT_VALUE_FLAG{$ENDIF}),
  686. TF);
  687. c.MapDSRowToMSQLRow[TF-1] := I;
  688. inc(TF);
  689. end
  690. end;
  691. // Writeln('MySQL: Finished adding fielddefs');
  692. end;
  693. function TConnectionName.Fetch(cursor: TSQLCursor): boolean;
  694. Var
  695. C : TCursorName;
  696. begin
  697. C:=Cursor as TCursorName;
  698. C.Row:=MySQL_Fetch_row(C.FRes);
  699. Result:=(C.Row<>Nil);
  700. if Result then
  701. C.Lengths := mysql_fetch_lengths(C.FRes)
  702. else
  703. C.Lengths := nil;
  704. end;
  705. function TConnectionName.LoadField(cursor : TSQLCursor;
  706. FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  707. var
  708. field: PMYSQL_FIELD;
  709. C : TCursorName;
  710. i : integer;
  711. begin
  712. // Writeln('LoadFieldsFromBuffer');
  713. C:=Cursor as TCursorName;
  714. if (C.Row=nil) or (C.Lengths=nil) then
  715. begin
  716. // Writeln('LoadFieldsFromBuffer: row=nil');
  717. MySQLError(FMySQL,SErrFetchingData,Self);
  718. end;
  719. i := c.MapDSRowToMSQLRow[FieldDef.FieldNo-1];
  720. field := mysql_fetch_field_direct(C.FRES, i);
  721. Result := MySQLWriteData(field, FieldDef, C.Row[i], Buffer, C.Lengths[i], CreateBlob);
  722. end;
  723. procedure TConnectionName.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  724. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  725. var
  726. C : TCursorName;
  727. i : integer;
  728. len : longint;
  729. begin
  730. C:=Cursor as TCursorName;
  731. if (C.Row=nil) or (C.Lengths=nil) then
  732. MySQLError(FMySQL,SErrFetchingData,Self);
  733. i := c.MapDSRowToMSQLRow[FieldDef.FieldNo-1];
  734. len := C.Lengths[i];
  735. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, len);
  736. Move(C.Row[i]^, ABlobBuf^.BlobBuffer^.Buffer^, len);
  737. ABlobBuf^.BlobBuffer^.Size := len;
  738. end;
  739. function InternalStrToInt(const S: string): integer;
  740. begin
  741. if S = '' then
  742. Result := 0
  743. else
  744. Result := StrToInt(S);
  745. end;
  746. function InternalStrToFloat(S: string): Extended;
  747. var
  748. I: Integer;
  749. Tmp: string;
  750. begin
  751. Tmp := '';
  752. for I := 1 to Length(S) do
  753. begin
  754. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  755. Tmp := Tmp + FormatSettings.DecimalSeparator
  756. else
  757. Tmp := Tmp + S[I];
  758. end;
  759. Result := StrToFloat(Tmp);
  760. end;
  761. function InternalStrToCurrency(S: string): Extended;
  762. var
  763. I: Integer;
  764. Tmp: string;
  765. begin
  766. Tmp := '';
  767. for I := 1 to Length(S) do
  768. begin
  769. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  770. Tmp := Tmp + FormatSettings.DecimalSeparator
  771. else
  772. Tmp := Tmp + S[I];
  773. end;
  774. Result := StrToCurr(Tmp);
  775. end;
  776. function InternalStrToDate(S: string): TDateTime;
  777. var
  778. EY, EM, ED: Word;
  779. begin
  780. EY := StrToInt(Copy(S,1,4));
  781. EM := StrToInt(Copy(S,6,2));
  782. ED := StrToInt(Copy(S,9,2));
  783. if (EY = 0) or (EM = 0) or (ED = 0) then
  784. Result:=0
  785. else
  786. Result:=EncodeDate(EY, EM, ED);
  787. end;
  788. function InternalStrToDateTime(S: string): TDateTime;
  789. var
  790. EY, EM, ED: Word;
  791. EH, EN, ES: Word;
  792. begin
  793. EY := StrToInt(Copy(S, 1, 4));
  794. EM := StrToInt(Copy(S, 6, 2));
  795. ED := StrToInt(Copy(S, 9, 2));
  796. EH := StrToInt(Copy(S, 12, 2));
  797. EN := StrToInt(Copy(S, 15, 2));
  798. ES := StrToInt(Copy(S, 18, 2));
  799. if (EY = 0) or (EM = 0) or (ED = 0) then
  800. Result := 0
  801. else
  802. Result := EncodeDate(EY, EM, ED);
  803. Result := ComposeDateTime(Result,EncodeTime(EH, EN, ES, 0));
  804. end;
  805. function InternalStrToTime(S: string): TDateTime;
  806. var
  807. EH, EM, ES: Word;
  808. p: integer;
  809. begin
  810. p := 1;
  811. EH := StrToInt(ExtractSubstr(S, p, [':'])); //hours can be 2 or 3 digits
  812. EM := StrToInt(ExtractSubstr(S, p, [':']));
  813. ES := StrToInt(ExtractSubstr(S, p, ['.']));
  814. Result := EncodeTimeInterval(EH, EM, ES, 0);
  815. end;
  816. function InternalStrToTimeStamp(S: string): TDateTime;
  817. var
  818. EY, EM, ED: Word;
  819. EH, EN, ES: Word;
  820. begin
  821. {$IFNDEF mysql40}
  822. EY := StrToInt(Copy(S, 1, 4));
  823. EM := StrToInt(Copy(S, 6, 2));
  824. ED := StrToInt(Copy(S, 9, 2));
  825. EH := StrToInt(Copy(S, 12, 2));
  826. EN := StrToInt(Copy(S, 15, 2));
  827. ES := StrToInt(Copy(S, 18, 2));
  828. {$ELSE}
  829. EY := StrToInt(Copy(S, 1, 4));
  830. EM := StrToInt(Copy(S, 5, 2));
  831. ED := StrToInt(Copy(S, 7, 2));
  832. EH := StrToInt(Copy(S, 9, 2));
  833. EN := StrToInt(Copy(S, 11, 2));
  834. ES := StrToInt(Copy(S, 13, 2));
  835. {$ENDIF}
  836. if (EY = 0) or (EM = 0) or (ED = 0) then
  837. Result := 0
  838. else
  839. Result := EncodeDate(EY, EM, ED);
  840. Result := Result + EncodeTime(EH, EN, ES, 0);
  841. end;
  842. function TConnectionName.MySQLWriteData(AField: PMYSQL_FIELD; FieldDef: TFieldDef; Source, Dest: PChar; Len: integer; out CreateBlob : boolean): Boolean;
  843. var
  844. VI: Integer;
  845. VL: LargeInt;
  846. VS: Smallint;
  847. VW: Word;
  848. VF: Double;
  849. VC: Currency;
  850. VD: TDateTime;
  851. VB: TBCD;
  852. Src : String;
  853. begin
  854. Result := False;
  855. CreateBlob := False;
  856. if Source = Nil then // If the pointer is NULL, the field is NULL
  857. exit;
  858. SetString(Src, Source, Len);
  859. if Len > FieldDef.Size then
  860. Len := FieldDef.Size;
  861. case FieldDef.DataType of
  862. ftSmallint:
  863. begin
  864. VS := InternalStrToInt(Src);
  865. Move(VS, Dest^, SizeOf(Smallint));
  866. end;
  867. ftWord:
  868. begin
  869. VW := InternalStrToInt(Src);
  870. Move(VW, Dest^, SizeOf(Word));
  871. end;
  872. ftInteger, ftAutoInc:
  873. begin
  874. VI := InternalStrToInt(Src);
  875. Move(VI, Dest^, SizeOf(Integer));
  876. end;
  877. ftLargeInt:
  878. begin
  879. {$IFDEF MYSQL50_UP}
  880. if AField^.ftype = FIELD_TYPE_BIT then
  881. begin
  882. VL := 0;
  883. for VI := 0 to Len-1 do
  884. VL := VL * 256 + PByte(Source+VI)^;
  885. end
  886. else
  887. {$ENDIF}
  888. if Src <> '' then
  889. VL := StrToInt64(Src)
  890. else
  891. VL := 0;
  892. Move(VL, Dest^, SizeOf(LargeInt));
  893. end;
  894. ftFloat:
  895. begin
  896. if Src <> '' then
  897. VF := InternalStrToFloat(Src)
  898. else
  899. VF := 0;
  900. Move(VF, Dest^, SizeOf(Double));
  901. end;
  902. ftBCD:
  903. begin
  904. VC := InternalStrToCurrency(Src);
  905. Move(VC, Dest^, SizeOf(Currency));
  906. end;
  907. ftFmtBCD:
  908. begin
  909. VB := StrToBCD(Src, FSQLFormatSettings);
  910. Move(VB, Dest^, SizeOf(TBCD));
  911. end;
  912. ftDate:
  913. begin
  914. if Src <> '' then
  915. VD := InternalStrToDate(Src)
  916. else
  917. VD := 0;
  918. Move(VD, Dest^, SizeOf(TDateTime));
  919. end;
  920. ftTime:
  921. begin
  922. if Src <> '' then
  923. VD := InternalStrToTime(Src)
  924. else
  925. VD := 0;
  926. Move(VD, Dest^, SizeOf(TDateTime));
  927. end;
  928. ftDateTime:
  929. begin
  930. if Src <> '' then
  931. if AField^.ftype = FIELD_TYPE_TIMESTAMP then
  932. VD := InternalStrToTimeStamp(Src)
  933. else
  934. VD := InternalStrToDateTime(Src)
  935. else
  936. VD := 0;
  937. Move(VD, Dest^, SizeOf(TDateTime));
  938. end;
  939. ftString, ftFixedChar:
  940. // String-fields which can contain more then dsMaxStringSize characters
  941. // are mapped to ftBlob fields, while their mysql-datatype is FIELD_TYPE_BLOB
  942. begin
  943. Move(Source^, Dest^, Len);
  944. (Dest+Len)^ := #0;
  945. end;
  946. ftVarBytes:
  947. begin
  948. PWord(Dest)^ := Len;
  949. Move(Source^, (Dest+sizeof(Word))^, Len);
  950. end;
  951. ftBytes:
  952. Move(Source^, Dest^, Len);
  953. ftBlob, ftMemo:
  954. CreateBlob := True;
  955. end;
  956. Result := True;
  957. end;
  958. procedure TConnectionName.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  959. var qry : TSQLQuery;
  960. begin
  961. if not assigned(Transaction) then
  962. DatabaseError(SErrConnTransactionnSet);
  963. qry := tsqlquery.Create(nil);
  964. qry.transaction := Transaction;
  965. qry.database := Self;
  966. with qry do
  967. begin
  968. ParseSQL := False;
  969. sql.clear;
  970. sql.add('show index from ' + TableName);
  971. open;
  972. end;
  973. while not qry.eof do with IndexDefs.AddIndexDef do
  974. begin
  975. Name := trim(qry.fieldbyname('Key_name').asstring);
  976. Fields := trim(qry.fieldbyname('Column_name').asstring);
  977. If Name = 'PRIMARY' then options := options + [ixPrimary];
  978. If qry.fieldbyname('Non_unique').asinteger = 0 then options := options + [ixUnique];
  979. qry.next;
  980. while (name = trim(qry.fieldbyname('Key_name').asstring)) and (not qry.eof) do
  981. begin
  982. Fields := Fields + ';' + trim(qry.fieldbyname('Column_name').asstring);
  983. qry.next;
  984. end;
  985. end;
  986. qry.close;
  987. qry.free;
  988. end;
  989. function TConnectionName.RowsAffected(cursor: TSQLCursor): TRowsCount;
  990. begin
  991. if assigned(cursor) then
  992. // Compile this without range-checking. RowsAffected can be -1, although
  993. // it's an unsigned integer. (small joke from the mysql-guys)
  994. // Without range-checking this goes ok. If Range is turned on, this results
  995. // in range-check errors.
  996. Result := (cursor as TCursorName).RowsAffected
  997. else
  998. Result := -1;
  999. end;
  1000. function TConnectionName.RefreshLastInsertID(Query: TCustomSQLQuery; Field: TField): Boolean;
  1001. begin
  1002. Field.AsLargeInt:=GetInsertID;
  1003. Result := True;
  1004. end;
  1005. constructor TConnectionName.Create(AOwner: TComponent);
  1006. const SingleBackQoutes: TQuoteChars = ('`','`');
  1007. begin
  1008. inherited Create(AOwner);
  1009. FConnOptions := [sqEscapeRepeat, sqEscapeSlash, sqImplicitTransaction, sqLastInsertID];
  1010. FieldNameQuoteChars:=SingleBackQoutes;
  1011. FMySQL := Nil;
  1012. end;
  1013. procedure TConnectionName.GetFieldNames(const TableName: string; List: TStrings);
  1014. begin
  1015. GetDBInfo(stColumns,TableName,'field',List);
  1016. end;
  1017. procedure TConnectionName.GetTableNames(List: TStrings; SystemTables: Boolean);
  1018. begin
  1019. GetDBInfo(stTables,'','tables_in_'+DatabaseName,List)
  1020. end;
  1021. function TConnectionName.GetConnectionInfo(InfoType: TConnInfoType): string;
  1022. begin
  1023. Result:='';
  1024. try
  1025. InitialiseMysql;
  1026. case InfoType of
  1027. citServerType:
  1028. Result:='MySQL';
  1029. citServerVersion:
  1030. if Connected then
  1031. Result:=format('%6.6d', [mysql_get_server_version(FMySQL)]);
  1032. citServerVersionString:
  1033. if Connected then
  1034. Result:=mysql_get_server_info(FMySQL);
  1035. citClientVersion:
  1036. Result:=format('%6.6d', [mysql_get_client_version()]);
  1037. citClientName:
  1038. Result:=TMySQLConnectionDef.LoadedLibraryName;
  1039. else
  1040. Result:=inherited GetConnectionInfo(InfoType);
  1041. end;
  1042. finally
  1043. ReleaseMysql;
  1044. end;
  1045. end;
  1046. function TConnectionName.GetTransactionHandle(trans: TSQLHandle): pointer;
  1047. begin
  1048. Result:=Nil;
  1049. end;
  1050. function TConnectionName.Commit(trans: TSQLHandle): boolean;
  1051. begin
  1052. //mysql_commit(FMySQL);
  1053. Result := (mysql_query(FMySQL, 'COMMIT') = 0) or ForcedClose;
  1054. if not Result then
  1055. MySQLError(FMySQL, SErrExecuting, Self);
  1056. end;
  1057. function TConnectionName.RollBack(trans: TSQLHandle): boolean;
  1058. begin
  1059. //mysql_rollback(FMySQL);
  1060. Result := (mysql_query(FMySQL, 'ROLLBACK') = 0) or ForcedClose;
  1061. if not Result then
  1062. MySQLError(FMySQL, SErrExecuting, Self);
  1063. end;
  1064. function TConnectionName.StartdbTransaction(trans: TSQLHandle; AParams : string): boolean;
  1065. begin
  1066. Result := mysql_query(FMySQL, 'START TRANSACTION') = 0;
  1067. if not Result then
  1068. MySQLError(FMySQL, SErrExecuting, Self);
  1069. end;
  1070. procedure TConnectionName.CommitRetaining(trans: TSQLHandle);
  1071. begin
  1072. {$IFDEF MYSQL50_UP}
  1073. if mysql_query(FMySQL, 'COMMIT AND CHAIN') <> 0 then
  1074. MySQLError(FMySQL, SErrExecuting, Self);
  1075. {$ELSE}
  1076. if mysql_query(FMySQL, 'COMMIT') <> 0 then
  1077. MySQLError(FMySQL, SErrExecuting, Self);
  1078. if mysql_query(FMySQL, 'START TRANSACTION') <> 0 then
  1079. MySQLError(FMySQL, SErrExecuting, Self);
  1080. {$ENDIF}
  1081. end;
  1082. procedure TConnectionName.RollBackRetaining(trans: TSQLHandle);
  1083. begin
  1084. {$IFDEF MYSQL50_UP}
  1085. if mysql_query(FMySQL, 'ROLLBACK AND CHAIN') <> 0 then
  1086. MySQLError(FMySQL, SErrExecuting, Self);
  1087. {$ELSE}
  1088. if mysql_query(FMySQL, 'ROLLBACK') <> 0 then
  1089. MySQLError(FMySQL, SErrExecuting, Self);
  1090. if mysql_query(FMySQL, 'START TRANSACTION') <> 0 then
  1091. MySQLError(FMySQL, SErrExecuting, Self);
  1092. {$ENDIF}
  1093. end;
  1094. function TConnectionName.GetSchemaInfoSQL(SchemaType: TSchemaType;
  1095. SchemaObjectName, SchemaPattern: string): string;
  1096. begin
  1097. case SchemaType of
  1098. stTables : result := 'show tables';
  1099. stColumns : result := 'show columns from ' + EscapeString(SchemaObjectName);
  1100. else
  1101. DatabaseError(SMetadataUnavailable)
  1102. end; {case}
  1103. end;
  1104. { TMySQLConnectionDef }
  1105. class function TMySQLConnectionDef.TypeName: String;
  1106. begin
  1107. Result:='MySQL '+MySQLVersion;
  1108. end;
  1109. class function TMySQLConnectionDef.ConnectionClass: TSQLConnectionClass;
  1110. begin
  1111. {$IFDEF mysql56}
  1112. Result:=TMySQL56Connection;
  1113. {$ELSE}
  1114. {$IfDef mysql55}
  1115. Result:=TMySQL55Connection;
  1116. {$ELSE}
  1117. {$IfDef mysql51}
  1118. Result:=TMySQL51Connection;
  1119. {$ELSE}
  1120. {$IfDef mysql50}
  1121. Result:=TMySQL50Connection;
  1122. {$ELSE}
  1123. {$IfDef mysql41}
  1124. Result:=TMySQL41Connection;
  1125. {$ELSE}
  1126. Result:=TMySQL40Connection;
  1127. {$EndIf}
  1128. {$EndIf}
  1129. {$endif}
  1130. {$endif}
  1131. {$ENDIF}
  1132. end;
  1133. class function TMySQLConnectionDef.Description: String;
  1134. begin
  1135. Result:='Connect to a MySQL '+MySQLVersion+'database directly via the client library';
  1136. end;
  1137. class function TMySQLConnectionDef.DefaultLibraryName: String;
  1138. begin
  1139. Result:=mysqlvlib;
  1140. end;
  1141. class function TMySQLConnectionDef.LoadFunction: TLibraryLoadFunction;
  1142. begin
  1143. Result:=@InitialiseMySQL;
  1144. end;
  1145. class function TMySQLConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  1146. begin
  1147. Result:=@ReleaseMySQL;
  1148. end;
  1149. class function TMySQLConnectionDef.LoadedLibraryName: string;
  1150. begin
  1151. Result:=MysqlLoadedLibrary;
  1152. end;
  1153. {$IFDEF mysql56}
  1154. initialization
  1155. RegisterConnection(TMySQL56ConnectionDef);
  1156. finalization
  1157. UnRegisterConnection(TMySQL56ConnectionDef);
  1158. {$ELSE}
  1159. {$IfDef mysql55}
  1160. initialization
  1161. RegisterConnection(TMySQL55ConnectionDef);
  1162. finalization
  1163. UnRegisterConnection(TMySQL55ConnectionDef);
  1164. {$else}
  1165. {$IfDef mysql51}
  1166. initialization
  1167. RegisterConnection(TMySQL51ConnectionDef);
  1168. finalization
  1169. UnRegisterConnection(TMySQL51ConnectionDef);
  1170. {$ELSE}
  1171. {$IfDef mysql50}
  1172. initialization
  1173. RegisterConnection(TMySQL50ConnectionDef);
  1174. finalization
  1175. UnRegisterConnection(TMySQL50ConnectionDef);
  1176. {$ELSE}
  1177. {$IfDef mysql41}
  1178. initialization
  1179. RegisterConnection(TMySQL41ConnectionDef);
  1180. finalization
  1181. UnRegisterConnection(TMySQL41ConnectionDef);
  1182. {$ELSE}
  1183. initialization
  1184. RegisterConnection(TMySQL40ConnectionDef);
  1185. finalization
  1186. UnRegisterConnection(TMySQL40ConnectionDef);
  1187. {$EndIf}
  1188. {$EndIf}
  1189. {$ENDIF}
  1190. {$endif}
  1191. {$ENDIF}
  1192. end.