mysqlconn.inc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. {$mode objfpc}{$H+}
  2. interface
  3. uses
  4. Classes, SysUtils,bufdataset,sqldb,db,dynlibs,
  5. {$IFDEF Mysql51}
  6. mysql51dyn;
  7. {$ELSE}
  8. {$IfDef mysql50}
  9. mysql50dyn;
  10. {$ELSE}
  11. {$IfDef mysql41}
  12. mysql41dyn;
  13. {$ELSE}
  14. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  15. mysql40dyn;
  16. {$ELSE}
  17. mysql40dyn;
  18. {$EndIf}
  19. {$EndIf}
  20. {$EndIf}
  21. {$endif}
  22. Const
  23. {$IFDEF Mysql51}
  24. MySQLVersion = '5.1';
  25. {$else}
  26. {$IfDef mysql50}
  27. MySQLVersion = '5.0';
  28. {$ELSE}
  29. {$IfDef mysql41}
  30. MySQLVersion = '4.1';
  31. {$ELSE}
  32. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  33. MySQLVersion = '4.0';
  34. {$ELSE}
  35. MySQLVersion = '4.0';
  36. {$EndIf}
  37. {$EndIf}
  38. {$EndIf}
  39. {$endif}
  40. Type
  41. TTransactionName = Class(TSQLHandle)
  42. protected
  43. end;
  44. { TCursorName }
  45. TCursorName = Class(TSQLCursor)
  46. protected
  47. FRes: PMYSQL_RES; { Record pointer }
  48. FNeedData : Boolean;
  49. FStatement : String;
  50. Row : MYSQL_ROW;
  51. RowsAffected : QWord;
  52. LastInsertID : QWord;
  53. ParamBinding : TParamBinding;
  54. ParamReplaceString : String;
  55. MapDSRowToMSQLRow : array of integer;
  56. end;
  57. { TConnectionName }
  58. TConnectionName = class (TSQLConnection)
  59. private
  60. FHostInfo: String;
  61. FServerInfo: String;
  62. FMySQL : PMySQL;
  63. function GetClientInfo: string;
  64. function GetServerStatus: String;
  65. procedure ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  66. procedure ExecuteDirectMySQL(const query : string);
  67. function EscapeString(const Str : string) : string;
  68. protected
  69. function StrToStatementType(s : string) : TStatementType; override;
  70. Procedure ConnectToServer; virtual;
  71. Procedure SelectDatabase; virtual;
  72. function MySQLDataType(AType: enum_field_types; ASize, ADecimals: Integer; var NewType: TFieldType; var NewSize: Integer): Boolean;
  73. function MySQLWriteData(AType: enum_field_types;ASize: Integer; AFieldType: TFieldType; Source, Dest: PChar; out CreateBlob : boolean): Boolean;
  74. // SQLConnection methods
  75. procedure DoInternalConnect; override;
  76. procedure DoInternalDisconnect; override;
  77. function GetHandle : pointer; override;
  78. function GetAsSQLText(Field : TField) : string; overload; override;
  79. function GetAsSQLText(Param : TParam) : string; overload; override;
  80. Function AllocateCursorHandle : TSQLCursor; override;
  81. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  82. Function AllocateTransactionHandle : TSQLHandle; override;
  83. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  84. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  85. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  86. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams); override;
  87. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  88. function Fetch(cursor : TSQLCursor) : boolean; override;
  89. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  90. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor;ATransaction : TSQLTransaction); override;
  91. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  92. function Commit(trans : TSQLHandle) : boolean; override;
  93. function RollBack(trans : TSQLHandle) : boolean; override;
  94. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  95. procedure CommitRetaining(trans : TSQLHandle); override;
  96. procedure RollBackRetaining(trans : TSQLHandle); override;
  97. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  98. procedure UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string); override;
  99. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  100. Public
  101. constructor Create(AOwner : TComponent); override;
  102. procedure GetFieldNames(const TableName : string; List : TStrings); override;
  103. procedure GetTableNames(List : TStrings; SystemTables : Boolean = false); override;
  104. procedure CreateDB; override;
  105. procedure DropDB; override;
  106. Property ServerInfo : String Read FServerInfo;
  107. Property HostInfo : String Read FHostInfo;
  108. property ClientInfo: string read GetClientInfo;
  109. property ServerStatus : String read GetServerStatus;
  110. published
  111. property DatabaseName;
  112. property HostName;
  113. property KeepConnection;
  114. property LoginPrompt;
  115. property Params;
  116. property Port stored false;
  117. property OnLogin;
  118. end;
  119. { TMySQLConnectionDef }
  120. TMySQLConnectionDef = Class(TConnectionDef)
  121. Class Function TypeName : String; override;
  122. Class Function ConnectionClass : TSQLConnectionClass; override;
  123. Class Function Description : String; override;
  124. end;
  125. EMySQLError = Class(Exception);
  126. {$IfDef mysql51}
  127. TMySQL51Connection = Class(TConnectionName);
  128. TMySQL51ConnectionDef = Class(TMySQLConnectionDef);
  129. TMySQL51Transaction = Class(TTransactionName);
  130. TMySQL51Cursor = Class(TCursorName);
  131. {$ELSE}
  132. {$IfDef mysql50}
  133. TMySQL50Connection = Class(TConnectionName);
  134. TMySQL50ConnectionDef = Class(TMySQLConnectionDef);
  135. TMySQL50Transaction = Class(TTransactionName);
  136. TMySQL50Cursor = Class(TCursorName);
  137. {$ELSE}
  138. {$IfDef mysql41}
  139. TMySQL41Connection = Class(TConnectionName);
  140. TMySQL41ConnectionDef = Class(TMySQLConnectionDef);
  141. TMySQL41Transaction = Class(TTransactionName);
  142. TMySQL41Cursor = Class(TCursorName);
  143. {$ELSE}
  144. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  145. TMySQLConnection = Class(TConnectionName);
  146. TMySQL40ConnectionDef = Class(TMySQLConnectionDef);
  147. TMySQLTransaction = Class(TTransactionName);
  148. TMySQLCursor = Class(TCursorName);
  149. {$ELSE}
  150. TMySQL40Connection = Class(TConnectionName);
  151. TMySQL40ConnectionDef = Class(TMySQLConnectionDef);
  152. TMySQL40Transaction = Class(TTransactionName);
  153. TMySQL40Cursor = Class(TCursorName);
  154. {$EndIf}
  155. {$EndIf}
  156. {$EndIf}
  157. {$ENDIF}
  158. implementation
  159. uses dbconst,ctypes,strutils;
  160. const
  161. Mysql_Option_Names : array[mysql_option] of string = ('MYSQL_OPT_CONNECT_TIMEOUT','MYSQL_OPT_COMPRESS',
  162. 'MYSQL_OPT_NAMED_PIPE','MYSQL_INIT_COMMAND',
  163. 'MYSQL_READ_DEFAULT_FILE','MYSQL_READ_DEFAULT_GROUP',
  164. 'MYSQL_SET_CHARSET_DIR','MYSQL_SET_CHARSET_NAME',
  165. 'MYSQL_OPT_LOCAL_INFILE','MYSQL_OPT_PROTOCOL',
  166. 'MYSQL_SHARED_MEMORY_BASE_NAME','MYSQL_OPT_READ_TIMEOUT',
  167. 'MYSQL_OPT_WRITE_TIMEOUT','MYSQL_OPT_USE_RESULT',
  168. 'MYSQL_OPT_USE_REMOTE_CONNECTION','MYSQL_OPT_USE_EMBEDDED_CONNECTION',
  169. 'MYSQL_OPT_GUESS_CONNECTION','MYSQL_SET_CLIENT_IP',
  170. 'MYSQL_SECURE_AUTH'
  171. {$IFDEF MYSQL50_UP}
  172. ,'MYSQL_REPORT_DATA_TRUNCATION', 'MYSQL_OPT_RECONNECT'
  173. {$ENDIF}
  174. );
  175. Resourcestring
  176. SErrServerConnectFailed = 'Server connect failed.';
  177. SErrDatabaseSelectFailed = 'failed to select database: %s';
  178. SErrDatabaseCreate = 'Failed to create database: %s';
  179. SErrDatabaseDrop = 'Failed to drop database: %s';
  180. SErrNoData = 'No data for record';
  181. SErrExecuting = 'Error executing query: %s';
  182. SErrFetchingdata = 'Error fetching row data: %s';
  183. SErrGettingResult = 'Error getting result set: %s';
  184. SErrNoQueryResult = 'No result from query.';
  185. SErrVersionMismatch = '%s can not work with the installed MySQL client version: Expected (%s), got (%s).';
  186. SErrSettingParameter = 'Error setting parameter "%s"';
  187. Procedure MySQlError(R : PMySQL;Msg: String;Comp : TComponent);
  188. Var
  189. MySQLMsg : String;
  190. begin
  191. If (R<>Nil) then
  192. begin
  193. MySQLMsg:=Strpas(mysql_error(R));
  194. DatabaseErrorFmt(Msg,[MySQLMsg],Comp);
  195. end
  196. else
  197. DatabaseError(Msg,Comp);
  198. end;
  199. function MysqlOption(const OptionName: string; out AMysql_Option: mysql_option) : boolean;
  200. var AMysql_Option_i: mysql_option;
  201. begin
  202. result := false;
  203. for AMysql_Option_i:=low(AMysql_Option) to high(AMysql_Option) do
  204. if sametext(Mysql_Option_Names[AMysql_Option_i],OptionName) then
  205. begin
  206. result := true;
  207. AMysql_Option:=AMysql_Option_i;
  208. break;
  209. end;
  210. end;
  211. { TConnectionName }
  212. function TConnectionName.StrToStatementType(s : string) : TStatementType;
  213. begin
  214. S:=Lowercase(s);
  215. if s = 'show' then exit(stSelect);
  216. result := inherited StrToStatementType(s);
  217. end;
  218. function TConnectionName.GetClientInfo: string;
  219. begin
  220. // To make it possible to call this if there's no connection yet
  221. InitialiseMysql;
  222. Try
  223. Result:=strpas(mysql_get_client_info());
  224. Finally
  225. ReleaseMysql;
  226. end;
  227. end;
  228. function TConnectionName.GetServerStatus: String;
  229. begin
  230. CheckConnected;
  231. Result := mysql_stat(FMYSQL);
  232. end;
  233. procedure TConnectionName.ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  234. Var
  235. APort : Cardinal;
  236. i,e: integer;
  237. AMysql_Option: mysql_option;
  238. OptStr: string;
  239. OptInt: cuint;
  240. Opt: pointer;
  241. begin
  242. HMySQL := mysql_init(HMySQL);
  243. APort:=Abs(StrToIntDef(Params.Values['Port'],0));
  244. for i := 0 to Params.Count-1 do
  245. begin
  246. if MysqlOption(params.Names[i],AMysql_Option) then
  247. begin
  248. OptStr:=params.ValueFromIndex[i];
  249. val(OptStr,OptInt,e);
  250. if e=0 then
  251. Opt := @OptInt
  252. else
  253. Opt := pchar(OptStr);
  254. if mysql_options(HMySQL,AMysql_Option,Opt) <> 0 then
  255. MySQlError(HMySQL,Format(SErrSettingParameter,[params.Names[i]]),Self);
  256. end;
  257. end;
  258. HMySQL:=mysql_real_connect(HMySQL,PChar(H),PChar(U),Pchar(P),Nil,APort,Nil,0);
  259. If (HMySQL=Nil) then
  260. MySQlError(Nil,SErrServerConnectFailed,Self);
  261. // MySQL _Server_ version 4.1 and later
  262. // major_version*10000 + minor_version *100 + sub_version
  263. if (trim(CharSet) <> '') and (4*10000 + 1*100 <= mysql_get_server_version(HMySQL)) then
  264. begin
  265. // Only available for mysql 5.0.7 and later...
  266. // if (mysql_set_character_set(HMySQL, PChar(CharSet)) <> 0) then
  267. if mysql_query(FMySQL,PChar('SET CHARACTER SET ''' + EscapeString(CharSet) +''''))<>0 then
  268. MySQLError(HMySQL,Format(SErrExecuting,[StrPas(mysql_error(HMySQL))]),Self);
  269. end;
  270. end;
  271. function TConnectionName.GetAsSQLText(Field : TField) : string;
  272. var esc_str : pchar;
  273. begin
  274. if (not assigned(field)) or field.IsNull then Result := 'Null'
  275. else if field.DataType = ftString then
  276. Result := '''' + EscapeString(field.AsString) + ''''
  277. else Result := inherited GetAsSqlText(field);
  278. end;
  279. function TConnectionName.GetAsSQLText(Param: TParam) : string;
  280. var esc_str : pchar;
  281. begin
  282. if (not assigned(param)) or param.IsNull then Result := 'Null'
  283. else if param.DataType in [ftString,ftBlob,ftMemo] then
  284. Result := '''' + EscapeString(Param.AsString) + ''''
  285. else Result := inherited GetAsSqlText(Param);
  286. end;
  287. procedure TConnectionName.ConnectToServer;
  288. Var
  289. H,U,P : String;
  290. begin
  291. H:=HostName;
  292. U:=UserName;
  293. P:=Password;
  294. ConnectMySQL(FMySQL,pchar(H),pchar(U),pchar(P));
  295. FServerInfo := strpas(mysql_get_server_info(FMYSQL));
  296. FHostInfo := strpas(mysql_get_host_info(FMYSQL));
  297. end;
  298. procedure TConnectionName.SelectDatabase;
  299. begin
  300. if mysql_select_db(FMySQL,pchar(DatabaseName))<>0 then
  301. MySQLError(FMySQL,SErrDatabaseSelectFailed,Self);
  302. end;
  303. procedure TConnectionName.CreateDB;
  304. begin
  305. ExecuteDirectMySQL('CREATE DATABASE ' +DatabaseName);
  306. end;
  307. procedure TConnectionName.DropDB;
  308. begin
  309. ExecuteDirectMySQL('DROP DATABASE ' +DatabaseName);
  310. end;
  311. procedure TConnectionName.ExecuteDirectMySQL(const query : string);
  312. var H,U,P : String;
  313. AMySQL : PMySQL;
  314. begin
  315. CheckDisConnected;
  316. InitialiseMysql;
  317. try
  318. H:=HostName;
  319. U:=UserName;
  320. P:=Password;
  321. AMySQL := nil;
  322. ConnectMySQL(AMySQL,pchar(H),pchar(U),pchar(P));
  323. try
  324. if mysql_query(AMySQL,pchar(query))<>0 then
  325. MySQLError(AMySQL,Format(SErrExecuting,[StrPas(mysql_error(AMySQL))]),Self);
  326. finally
  327. mysql_close(AMySQL);
  328. end;
  329. finally
  330. ReleaseMysql;
  331. end;
  332. end;
  333. function TConnectionName.EscapeString(const Str: string): string;
  334. var Len : integer;
  335. begin
  336. SetLength(result,length(str)*2+1);
  337. Len := mysql_real_escape_string(FMySQL,pchar(Result),pchar(Str),length(Str));
  338. SetLength(result,Len);
  339. end;
  340. procedure TConnectionName.DoInternalConnect;
  341. var
  342. FullVersion,
  343. ClientVerStr: string;
  344. begin
  345. InitialiseMysql;
  346. Fullversion:=strpas(mysql_get_client_info());
  347. ClientVerStr := copy(FullVersion,1,3);
  348. If (ClientVerStr<>MySQLVersion) then
  349. Raise EInOutError.CreateFmt(SErrVersionMisMatch,[ClassName,MySQLVersion,FullVersion]);
  350. inherited DoInternalConnect;
  351. ConnectToServer;
  352. SelectDatabase;
  353. end;
  354. procedure TConnectionName.DoInternalDisconnect;
  355. begin
  356. inherited DoInternalDisconnect;
  357. mysql_close(FMySQL);
  358. FMySQL:=Nil;
  359. ReleaseMysql;
  360. end;
  361. function TConnectionName.GetHandle: pointer;
  362. begin
  363. Result:=FMySQL;
  364. end;
  365. function TConnectionName.AllocateCursorHandle: TSQLCursor;
  366. begin
  367. {$IfDef mysql51}
  368. Result:=TMySQL51Cursor.Create;
  369. {$ELSE}
  370. {$IfDef mysql50}
  371. Result:=TMySQL50Cursor.Create;
  372. {$ELSE}
  373. {$IfDef mysql41}
  374. Result:=TMySQL41Cursor.Create;
  375. {$ELSE}
  376. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  377. Result:=TMySQLCursor.Create;
  378. {$ELSE}
  379. Result:=TMySQL40Cursor.Create;
  380. {$EndIf}
  381. {$EndIf}
  382. {$EndIf}
  383. {$EndIf}
  384. end;
  385. Procedure TConnectionName.DeAllocateCursorHandle(var cursor : TSQLCursor);
  386. begin
  387. FreeAndNil(cursor);
  388. end;
  389. function TConnectionName.AllocateTransactionHandle: TSQLHandle;
  390. begin
  391. // Result:=TTransactionName.Create;
  392. Result := nil;
  393. end;
  394. procedure TConnectionName.PrepareStatement(cursor: TSQLCursor;
  395. ATransaction: TSQLTransaction; buf: string;AParams : TParams);
  396. begin
  397. // if assigned(AParams) and (AParams.count > 0) then
  398. // DatabaseError('Parameters (not) yet supported for the MySQL SqlDB connection.',self);
  399. With Cursor as TCursorName do
  400. begin
  401. FStatement:=Buf;
  402. if assigned(AParams) and (AParams.count > 0) then
  403. FStatement := AParams.ParseSQL(FStatement,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psSimulated,paramBinding,ParamReplaceString);
  404. if FStatementType=stSelect then
  405. FNeedData:=True;
  406. end
  407. end;
  408. procedure TConnectionName.UnPrepareStatement(cursor: TSQLCursor);
  409. begin
  410. // do nothing
  411. end;
  412. procedure TConnectionName.FreeFldBuffers(cursor: TSQLCursor);
  413. Var
  414. C : TCursorName;
  415. begin
  416. C:=Cursor as TCursorName;
  417. if c.FStatementType=stSelect then
  418. c.FNeedData:=False;
  419. If (C.FRes<>Nil) then
  420. begin
  421. Mysql_free_result(C.FRes);
  422. C.FRes:=Nil;
  423. end;
  424. SetLength(c.MapDSRowToMSQLRow,0);
  425. inherited;
  426. end;
  427. procedure TConnectionName.Execute(cursor: TSQLCursor;
  428. atransaction: tSQLtransaction;AParams : TParams);
  429. Var
  430. C : TCursorName;
  431. i : integer;
  432. ParamNames,ParamValues : array of string;
  433. begin
  434. C:=Cursor as TCursorName;
  435. If (C.FRes=Nil) then
  436. begin
  437. if Assigned(AParams) and (AParams.count > 0) then
  438. begin
  439. setlength(ParamNames,AParams.Count);
  440. setlength(ParamValues,AParams.Count);
  441. for i := 0 to AParams.count -1 do
  442. begin
  443. ParamNames[AParams.count-i-1] := C.ParamReplaceString+inttostr(AParams[i].Index+1);
  444. ParamValues[AParams.count-i-1] := GetAsSQLText(AParams[i]);
  445. end;
  446. // paramreplacestring kan een probleem geven bij postgres als hij niet meer gewoon $ is?
  447. C.FStatement := stringsreplace(C.FStatement,ParamNames,ParamValues,[rfReplaceAll]);
  448. end;
  449. if mysql_query(FMySQL,Pchar(C.FStatement))<>0 then
  450. MySQLError(FMYSQL,Format(SErrExecuting,[StrPas(mysql_error(FMySQL))]),Self)
  451. else
  452. begin
  453. C.RowsAffected := mysql_affected_rows(FMYSQL);
  454. C.LastInsertID := mysql_insert_id(FMYSQL);
  455. if C.FNeedData then
  456. C.FRes:=mysql_store_result(FMySQL);
  457. end;
  458. end;
  459. end;
  460. function TConnectionName.MySQLDataType(AType: enum_field_types; ASize, ADecimals: Integer;
  461. var NewType: TFieldType; var NewSize: Integer): Boolean;
  462. begin
  463. Result := True;
  464. case AType of
  465. FIELD_TYPE_LONGLONG:
  466. begin
  467. NewType := ftLargeint;
  468. NewSize := 0;
  469. end;
  470. FIELD_TYPE_TINY, FIELD_TYPE_SHORT:
  471. begin
  472. NewType := ftSmallint;
  473. NewSize := 0;
  474. end;
  475. FIELD_TYPE_LONG, FIELD_TYPE_INT24:
  476. begin
  477. NewType := ftInteger;
  478. NewSize := 0;
  479. end;
  480. {$ifdef mysql50_up}
  481. FIELD_TYPE_NEWDECIMAL,
  482. {$endif}
  483. FIELD_TYPE_DECIMAL: if ADecimals < 5 then
  484. begin
  485. NewType := ftBCD;
  486. NewSize := ADecimals;
  487. end
  488. else
  489. begin
  490. NewType := ftFloat;
  491. NewSize := 0;
  492. end;
  493. FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  494. begin
  495. NewType := ftFloat;
  496. NewSize := 0;
  497. end;
  498. FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  499. begin
  500. NewType := ftDateTime;
  501. NewSize := 0;
  502. end;
  503. FIELD_TYPE_DATE:
  504. begin
  505. NewType := ftDate;
  506. NewSize := 0;
  507. end;
  508. FIELD_TYPE_TIME:
  509. begin
  510. NewType := ftTime;
  511. NewSize := 0;
  512. end;
  513. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  514. begin
  515. // Since mysql server version 5.0.3 string-fields with a length of more
  516. // then 256 characters are suported
  517. if ASize>dsMaxStringSize then
  518. begin
  519. NewType := ftMemo;
  520. NewSize := 0;
  521. end
  522. else
  523. begin
  524. NewType := ftString;
  525. NewSize := ASize;
  526. end;
  527. end;
  528. FIELD_TYPE_BLOB:
  529. begin
  530. NewType := ftBlob;
  531. NewSize := 0;
  532. end
  533. else
  534. Result := False;
  535. end;
  536. end;
  537. procedure TConnectionName.AddFieldDefs(cursor: TSQLCursor;
  538. FieldDefs: TfieldDefs);
  539. var
  540. C : TCursorName;
  541. I, TF, FC: Integer;
  542. field: PMYSQL_FIELD;
  543. DFT: TFieldType;
  544. DFS: Integer;
  545. begin
  546. // Writeln('MySQL: Adding fielddefs');
  547. C:=(Cursor as TCursorName);
  548. If (C.FRes=Nil) then
  549. begin
  550. // Writeln('res is nil');
  551. MySQLError(FMySQL,SErrNoQueryResult,Self);
  552. end;
  553. // Writeln('MySQL: have result');
  554. FC:=mysql_num_fields(C.FRes);
  555. SetLength(c.MapDSRowToMSQLRow,FC);
  556. TF := 1;
  557. For I:= 0 to FC-1 do
  558. begin
  559. field := mysql_fetch_field_direct(C.FRES, I);
  560. // Writeln('MySQL: creating fielddef ',I+1);
  561. if MySQLDataType(field^.ftype, field^.length, field^.decimals, DFT, DFS) then
  562. begin
  563. TFieldDef.Create(FieldDefs, FieldDefs.MakeNameUnique(field^.name), DFT, DFS, False, TF);
  564. c.MapDSRowToMSQLRow[TF-1] := I;
  565. inc(TF);
  566. end
  567. end;
  568. // Writeln('MySQL: Finished adding fielddefs');
  569. end;
  570. function TConnectionName.Fetch(cursor: TSQLCursor): boolean;
  571. Var
  572. C : TCursorName;
  573. begin
  574. C:=Cursor as TCursorName;
  575. C.Row:=MySQL_Fetch_row(C.FRes);
  576. Result:=(C.Row<>Nil);
  577. end;
  578. function TConnectionName.LoadField(cursor : TSQLCursor;
  579. FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  580. var
  581. field: PMYSQL_FIELD;
  582. row : MYSQL_ROW;
  583. C : TCursorName;
  584. begin
  585. // Writeln('LoadFieldsFromBuffer');
  586. C:=Cursor as TCursorName;
  587. if C.Row=nil then
  588. begin
  589. // Writeln('LoadFieldsFromBuffer: row=nil');
  590. MySQLError(FMySQL,SErrFetchingData,Self);
  591. end;
  592. Row:=C.Row;
  593. inc(Row,c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]);
  594. field := mysql_fetch_field_direct(C.FRES, c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]);
  595. Result := MySQLWriteData(field^.ftype, field^.length, FieldDef.DataType, Row^, Buffer, CreateBlob);
  596. end;
  597. procedure TConnectionName.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  598. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  599. var
  600. row : MYSQL_ROW;
  601. C : TCursorName;
  602. li : longint;
  603. Lengths : pculong;
  604. begin
  605. C:=Cursor as TCursorName;
  606. if C.Row=nil then
  607. MySQLError(FMySQL,SErrFetchingData,Self);
  608. Row:=C.Row;
  609. inc(Row,c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]);
  610. Lengths := mysql_fetch_lengths(c.FRes);
  611. li := Lengths[c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]];
  612. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  613. Move(pchar(row^)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  614. ABlobBuf^.BlobBuffer^.Size := li;
  615. end;
  616. function InternalStrToFloat(S: string): Extended;
  617. var
  618. I: Integer;
  619. Tmp: string;
  620. begin
  621. Tmp := '';
  622. for I := 1 to Length(S) do
  623. begin
  624. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  625. Tmp := Tmp + DecimalSeparator
  626. else
  627. Tmp := Tmp + S[I];
  628. end;
  629. Result := StrToFloat(Tmp);
  630. end;
  631. function InternalStrToCurrency(S: string): Extended;
  632. var
  633. I: Integer;
  634. Tmp: string;
  635. begin
  636. Tmp := '';
  637. for I := 1 to Length(S) do
  638. begin
  639. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  640. Tmp := Tmp + DecimalSeparator
  641. else
  642. Tmp := Tmp + S[I];
  643. end;
  644. Result := StrToCurr(Tmp);
  645. end;
  646. function InternalStrToDate(S: string): TDateTime;
  647. var
  648. EY, EM, ED: Word;
  649. begin
  650. EY := StrToInt(Copy(S,1,4));
  651. EM := StrToInt(Copy(S,6,2));
  652. ED := StrToInt(Copy(S,9,2));
  653. if (EY = 0) or (EM = 0) or (ED = 0) then
  654. Result:=0
  655. else
  656. Result:=EncodeDate(EY, EM, ED);
  657. end;
  658. function InternalStrToDateTime(S: string): TDateTime;
  659. var
  660. EY, EM, ED: Word;
  661. EH, EN, ES: Word;
  662. begin
  663. EY := StrToInt(Copy(S, 1, 4));
  664. EM := StrToInt(Copy(S, 6, 2));
  665. ED := StrToInt(Copy(S, 9, 2));
  666. EH := StrToInt(Copy(S, 12, 2));
  667. EN := StrToInt(Copy(S, 15, 2));
  668. ES := StrToInt(Copy(S, 18, 2));
  669. if (EY = 0) or (EM = 0) or (ED = 0) then
  670. Result := 0
  671. else
  672. Result := EncodeDate(EY, EM, ED);
  673. Result := Result + EncodeTime(EH, EN, ES, 0);
  674. end;
  675. function InternalStrToTime(S: string): TDateTime;
  676. var
  677. EH, EM, ES: Word;
  678. begin
  679. EH := StrToInt(Copy(S, 1, 2));
  680. EM := StrToInt(Copy(S, 4, 2));
  681. ES := StrToInt(Copy(S, 7, 2));
  682. Result := EncodeTime(EH, EM, ES, 0);
  683. end;
  684. function InternalStrToTimeStamp(S: string): TDateTime;
  685. var
  686. EY, EM, ED: Word;
  687. EH, EN, ES: Word;
  688. begin
  689. {$IFNDEF mysql40}
  690. EY := StrToInt(Copy(S, 1, 4));
  691. EM := StrToInt(Copy(S, 6, 2));
  692. ED := StrToInt(Copy(S, 9, 2));
  693. EH := StrToInt(Copy(S, 12, 2));
  694. EN := StrToInt(Copy(S, 15, 2));
  695. ES := StrToInt(Copy(S, 18, 2));
  696. {$ELSE}
  697. EY := StrToInt(Copy(S, 1, 4));
  698. EM := StrToInt(Copy(S, 5, 2));
  699. ED := StrToInt(Copy(S, 7, 2));
  700. EH := StrToInt(Copy(S, 9, 2));
  701. EN := StrToInt(Copy(S, 11, 2));
  702. ES := StrToInt(Copy(S, 13, 2));
  703. {$ENDIF}
  704. if (EY = 0) or (EM = 0) or (ED = 0) then
  705. Result := 0
  706. else
  707. Result := EncodeDate(EY, EM, ED);
  708. Result := Result + EncodeTime(EH, EN, ES, 0);;
  709. end;
  710. function TConnectionName.MySQLWriteData(AType: enum_field_types;ASize: Integer; AFieldType: TFieldType; Source, Dest: PChar; out CreateBlob : boolean): Boolean;
  711. var
  712. VI: Integer;
  713. VL: LargeInt;
  714. VS: Smallint;
  715. VF: Double;
  716. VC: Currency;
  717. VD: TDateTime;
  718. Src : String;
  719. begin
  720. Result := False;
  721. CreateBlob := False;
  722. if Source = Nil then
  723. exit;
  724. Src:=StrPas(Source);
  725. case AType of
  726. FIELD_TYPE_TINY, FIELD_TYPE_SHORT:
  727. begin
  728. if (Src<>'') then
  729. VS := StrToInt(Src)
  730. else
  731. VS := 0;
  732. Move(VS, Dest^, SizeOf(smallint));
  733. end;
  734. FIELD_TYPE_LONG, FIELD_TYPE_INT24:
  735. begin
  736. if (Src<>'') then
  737. VI := StrToInt(Src)
  738. else
  739. VI := 0;
  740. Move(VI, Dest^, SizeOf(Integer));
  741. end;
  742. FIELD_TYPE_LONGLONG:
  743. begin
  744. if (Src<>'') then
  745. VL := StrToInt64(Src)
  746. else
  747. VL := 0;
  748. Move(VL, Dest^, SizeOf(LargeInt));
  749. end;
  750. {$ifdef mysql50_up}
  751. FIELD_TYPE_NEWDECIMAL,
  752. {$endif}
  753. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  754. if AFieldType = ftBCD then
  755. begin
  756. VC := InternalStrToCurrency(Src);
  757. Move(VC, Dest^, SizeOf(Currency));
  758. end
  759. else
  760. begin
  761. if Src <> '' then
  762. VF := InternalStrToFloat(Src)
  763. else
  764. VF := 0;
  765. Move(VF, Dest^, SizeOf(Double));
  766. end;
  767. FIELD_TYPE_TIMESTAMP:
  768. begin
  769. if Src <> '' then
  770. VD := InternalStrToTimeStamp(Src)
  771. else
  772. VD := 0;
  773. Move(VD, Dest^, SizeOf(TDateTime));
  774. end;
  775. FIELD_TYPE_DATETIME:
  776. begin
  777. if Src <> '' then
  778. VD := InternalStrToDateTime(Src)
  779. else
  780. VD := 0;
  781. Move(VD, Dest^, SizeOf(TDateTime));
  782. end;
  783. FIELD_TYPE_DATE:
  784. begin
  785. if Src <> '' then
  786. VD := InternalStrToDate(Src)
  787. else
  788. VD := 0;
  789. Move(VD, Dest^, SizeOf(TDateTime));
  790. end;
  791. FIELD_TYPE_TIME:
  792. begin
  793. if Src <> '' then
  794. VD := InternalStrToTime(Src)
  795. else
  796. VD := 0;
  797. Move(VD, Dest^, SizeOf(TDateTime));
  798. end;
  799. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  800. begin
  801. { Write('Moving string of size ',asize,' : ');
  802. P:=Source;
  803. If (P<>nil) then
  804. While P[0]<>#0 do
  805. begin
  806. Write(p[0]);
  807. inc(p);
  808. end;
  809. Writeln;
  810. }
  811. // String-fields which can contain more then dsMaxStringSize characters
  812. // are mapped to ftBlob fields, while their mysql-datatype is FIELD_TYPE_BLOB
  813. if AFieldType in [ftBlob,ftMemo] then
  814. CreateBlob := True
  815. else if Src<> '' then
  816. Move(Source^, Dest^, ASize)
  817. else
  818. Dest^ := #0;
  819. end;
  820. FIELD_TYPE_BLOB:
  821. CreateBlob := True;
  822. end;
  823. Result := True;
  824. end;
  825. procedure TConnectionName.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  826. var qry : TSQLQuery;
  827. begin
  828. if not assigned(Transaction) then
  829. DatabaseError(SErrConnTransactionnSet);
  830. qry := tsqlquery.Create(nil);
  831. qry.transaction := Transaction;
  832. qry.database := Self;
  833. with qry do
  834. begin
  835. ParseSQL := False;
  836. sql.clear;
  837. sql.add('show index from ' + TableName);
  838. open;
  839. end;
  840. while not qry.eof do with IndexDefs.AddIndexDef do
  841. begin
  842. Name := trim(qry.fieldbyname('Key_name').asstring);
  843. Fields := trim(qry.fieldbyname('Column_name').asstring);
  844. If Name = 'PRIMARY' then options := options + [ixPrimary];
  845. If qry.fieldbyname('Non_unique').asinteger = 0 then options := options + [ixUnique];
  846. qry.next;
  847. while (name = trim(qry.fieldbyname('Key_name').asstring)) and (not qry.eof) do
  848. begin
  849. Fields := Fields + ';' + trim(qry.fieldbyname('Column_name').asstring);
  850. qry.next;
  851. end;
  852. end;
  853. qry.close;
  854. qry.free;
  855. end;
  856. function TConnectionName.RowsAffected(cursor: TSQLCursor): TRowsCount;
  857. begin
  858. if assigned(cursor) then
  859. // Compile this without range-checking. RowsAffected can be -1, although
  860. // it's an unsigned integer. (small joke from the mysql-guys)
  861. // Without range-checking this goes ok. If Range is turned on, this results
  862. // in range-check errors.
  863. Result := (cursor as TCursorName).RowsAffected
  864. else
  865. Result := -1;
  866. end;
  867. constructor TConnectionName.Create(AOwner: TComponent);
  868. const SingleBackQoutes: TQuoteChars = ('`','`');
  869. begin
  870. inherited Create(AOwner);
  871. FConnOptions := FConnOptions + [sqEscapeRepeat] + [sqEscapeSlash];
  872. FieldNameQuoteChars:=SingleBackQoutes;
  873. FMySQL := Nil;
  874. end;
  875. procedure TConnectionName.GetFieldNames(const TableName: string; List: TStrings);
  876. begin
  877. GetDBInfo(stColumns,TableName,'field',List);
  878. end;
  879. procedure TConnectionName.GetTableNames(List: TStrings; SystemTables: Boolean);
  880. begin
  881. GetDBInfo(stTables,'','tables_in_'+DatabaseName,List)
  882. end;
  883. function TConnectionName.GetTransactionHandle(trans: TSQLHandle): pointer;
  884. begin
  885. Result:=Nil;
  886. end;
  887. function TConnectionName.Commit(trans: TSQLHandle): boolean;
  888. begin
  889. // Do nothing.
  890. end;
  891. function TConnectionName.RollBack(trans: TSQLHandle): boolean;
  892. begin
  893. // Do nothing
  894. end;
  895. function TConnectionName.StartdbTransaction(trans: TSQLHandle; AParams : string): boolean;
  896. begin
  897. // Do nothing
  898. end;
  899. procedure TConnectionName.CommitRetaining(trans: TSQLHandle);
  900. begin
  901. // Do nothing
  902. end;
  903. procedure TConnectionName.RollBackRetaining(trans: TSQLHandle);
  904. begin
  905. // Do nothing
  906. end;
  907. function TConnectionName.GetSchemaInfoSQL(SchemaType: TSchemaType;
  908. SchemaObjectName, SchemaPattern: string): string;
  909. begin
  910. case SchemaType of
  911. stTables : result := 'show tables';
  912. stColumns : result := 'show columns from ' + EscapeString(SchemaObjectName);
  913. else
  914. DatabaseError(SMetadataUnavailable)
  915. end; {case}
  916. end;
  917. { TMySQLConnectionDef }
  918. class function TMySQLConnectionDef.TypeName: String;
  919. begin
  920. Result:='MySQL '+MySQLVersion;
  921. end;
  922. class function TMySQLConnectionDef.ConnectionClass: TSQLConnectionClass;
  923. begin
  924. {$IfDef mysql51}
  925. Result:=TMySQL51Connection;
  926. {$ELSE}
  927. {$IfDef mysql50}
  928. Result:=TMySQL50Connection;
  929. {$ELSE}
  930. {$IfDef mysql41}
  931. Result:=TMySQL41Connection;
  932. {$ELSE}
  933. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  934. Result:=TMySQLConnection;
  935. {$ELSE}
  936. Result:=TMySQL40Connection;
  937. {$EndIf}
  938. {$EndIf}
  939. {$EndIf}
  940. {$endif}
  941. end;
  942. class function TMySQLConnectionDef.Description: String;
  943. begin
  944. Result:='Connect to a MySQL '+MySQLVersion+'database directly via the client library';
  945. end;
  946. {$IfDef mysql51}
  947. initialization
  948. RegisterConnection(TMySQL51ConnectionDef);
  949. finalization
  950. UnRegisterConnection(TMySQL51ConnectionDef);
  951. {$ELSE}
  952. {$IfDef mysql50}
  953. initialization
  954. RegisterConnection(TMySQL50ConnectionDef);
  955. finalization
  956. UnRegisterConnection(TMySQL50ConnectionDef);
  957. {$ELSE}
  958. {$IfDef mysql41}
  959. initialization
  960. RegisterConnection(TMySQL41ConnectionDef);
  961. finalization
  962. UnRegisterConnection(TMySQL41ConnectionDef);
  963. {$ELSE}
  964. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  965. initialization
  966. RegisterConnection(TMySQL40ConnectionDef);
  967. finalization
  968. UnRegisterConnection(TMySQL40ConnectionDef);
  969. {$ELSE}
  970. initialization
  971. RegisterConnection(TMySQL40ConnectionDef);
  972. finalization
  973. UnRegisterConnection(TMySQL40ConnectionDef);
  974. {$EndIf}
  975. {$EndIf}
  976. {$EndIf}
  977. {$ENDIF}
  978. end.