mysqlconn.inc 37 KB

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