mysql4conn.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. unit mysql4conn;
  2. {$mode objfpc}{$H+}
  3. {$Define LinkDynamically}
  4. interface
  5. uses
  6. Classes, SysUtils,sqldb,db,
  7. {$IfDef LinkDynamically}
  8. mysql4dyn,mysql4_comdyn;
  9. {$Else}
  10. mysql4,mysql4_com;
  11. {$EndIf}
  12. Type
  13. TMySQLTransaction = Class(TSQLHandle)
  14. protected
  15. end;
  16. TMySQLCursor = Class(TSQLCursor)
  17. protected
  18. FQMySQL : PMySQL;
  19. FRes: PMYSQL_RES; { Record pointer }
  20. FNeedData : Boolean;
  21. FStatement : String;
  22. Row : TMYSQL_ROW;
  23. RowsAffected : QWord;
  24. LastInsertID : QWord;
  25. end;
  26. TMySQLConnection = class (TSQLConnection)
  27. private
  28. FDialect: integer;
  29. FHostInfo: String;
  30. FServerInfo: String;
  31. FMySQL : PMySQL;
  32. function GetClientInfo: string;
  33. function GetServerStatus: String;
  34. procedure ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  35. protected
  36. function StrToStatementType(s : string) : TStatementType; override;
  37. Procedure ConnectToServer; virtual;
  38. Procedure SelectDatabase; virtual;
  39. function MySQLDataType(AType: enum_field_types; ASize: Integer; var NewType: TFieldType; var NewSize: Integer): Boolean;
  40. function MySQLWriteData(AType: enum_field_types; ASize: Integer; Source, Dest: PChar): Integer;
  41. // SQLConnection methods
  42. procedure DoInternalConnect; override;
  43. procedure DoInternalDisconnect; override;
  44. function GetHandle : pointer; override;
  45. Function AllocateCursorHandle : TSQLCursor; override;
  46. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  47. Function AllocateTransactionHandle : TSQLHandle; override;
  48. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  49. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  50. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  51. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams); override;
  52. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  53. function Fetch(cursor : TSQLCursor) : boolean; override;
  54. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer) : boolean; override;
  55. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  56. function Commit(trans : TSQLHandle) : boolean; override;
  57. function RollBack(trans : TSQLHandle) : boolean; override;
  58. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  59. procedure CommitRetaining(trans : TSQLHandle); override;
  60. procedure RollBackRetaining(trans : TSQLHandle); override;
  61. procedure UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string); override;
  62. Public
  63. Property ServerInfo : String Read FServerInfo;
  64. Property HostInfo : String Read FHostInfo;
  65. property ClientInfo: string read GetClientInfo;
  66. property ServerStatus : String read GetServerStatus;
  67. published
  68. property Dialect : integer read FDialect write FDialect;
  69. property DatabaseName;
  70. property HostName;
  71. property KeepConnection;
  72. property LoginPrompt;
  73. property Params;
  74. property OnLogin;
  75. end;
  76. EMySQLError = Class(Exception);
  77. implementation
  78. uses dbconst;
  79. { TMySQLConnection }
  80. Resourcestring
  81. SErrServerConnectFailed = 'Server connect failed.';
  82. SErrDatabaseSelectFailed = 'failed to select database: %s';
  83. SErrDatabaseCreate = 'Failed to create database: %s';
  84. SErrDatabaseDrop = 'Failed to drop database: %s';
  85. SErrNoData = 'No data for record';
  86. SErrExecuting = 'Error executing query: %s';
  87. SErrFetchingdata = 'Error fetching row data: %s';
  88. SErrGettingResult = 'Error getting result set: %s';
  89. SErrNoQueryResult = 'No result from query.';
  90. Procedure MySQlError(R : PMySQL;Msg: String;Comp : TComponent);
  91. Var
  92. MySQLMsg : String;
  93. begin
  94. If (R<>Nil) then
  95. begin
  96. MySQLMsg:=Strpas(mysql_error(R));
  97. DatabaseErrorFmt(Msg,[MySQLMsg],Comp);
  98. end
  99. else
  100. DatabaseError(Msg,Comp);
  101. end;
  102. function TMySQLConnection.StrToStatementType(s : string) : TStatementType;
  103. begin
  104. S:=Lowercase(s);
  105. if s = 'show' then exit(stSelect);
  106. result := inherited StrToStatementType(s);
  107. end;
  108. function TMySQLConnection.GetClientInfo: string;
  109. begin
  110. {$IfDef LinkDynamically}
  111. // To make it possible to call this if there's no connection yet
  112. InitialiseMysql4;
  113. {$EndIf}
  114. Result:=strpas(mysql_get_client_info());
  115. {$IfDef LinkDynamically}
  116. ReleaseMysql4;
  117. {$EndIf}
  118. end;
  119. function TMySQLConnection.GetServerStatus: String;
  120. begin
  121. CheckConnected;
  122. Result := mysql_stat(FMYSQL);
  123. end;
  124. procedure TMySQLConnection.ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  125. begin
  126. HMySQL := mysql_init(HMySQL);
  127. HMySQL:=mysql_real_connect(HMySQL,PChar(H),PChar(U),Pchar(P),Nil,0,Nil,0);
  128. If (HMySQL=Nil) then
  129. MySQlError(Nil,SErrServerConnectFailed,Self);
  130. end;
  131. procedure TMySQLConnection.ConnectToServer;
  132. Var
  133. H,U,P : String;
  134. begin
  135. H:=HostName;
  136. U:=UserName;
  137. P:=Password;
  138. ConnectMySQL(FMySQL,pchar(H),pchar(U),pchar(P));
  139. FServerInfo := strpas(mysql_get_server_info(FMYSQL));
  140. FHostInfo := strpas(mysql_get_host_info(FMYSQL));
  141. end;
  142. procedure TMySQLConnection.SelectDatabase;
  143. begin
  144. if mysql_select_db(FMySQL,pchar(DatabaseName))<>0 then
  145. MySQLError(FMySQL,SErrDatabaseSelectFailed,Self);
  146. end;
  147. procedure TMySQLConnection.DoInternalConnect;
  148. begin
  149. {$IfDef LinkDynamically}
  150. InitialiseMysql4;
  151. {$EndIf}
  152. inherited DoInternalConnect;
  153. ConnectToServer;
  154. SelectDatabase;
  155. end;
  156. procedure TMySQLConnection.DoInternalDisconnect;
  157. begin
  158. inherited DoInternalDisconnect;
  159. mysql_close(FMySQL);
  160. FMySQL:=Nil;
  161. {$IfDef LinkDynamically}
  162. ReleaseMysql4;
  163. {$EndIf}
  164. end;
  165. function TMySQLConnection.GetHandle: pointer;
  166. begin
  167. Result:=FMySQL;
  168. end;
  169. function TMySQLConnection.AllocateCursorHandle: TSQLCursor;
  170. begin
  171. Result:=TMySQLCursor.Create;
  172. end;
  173. Procedure TMySQLConnection.DeAllocateCursorHandle(var cursor : TSQLCursor);
  174. begin
  175. FreeAndNil(cursor);
  176. end;
  177. function TMySQLConnection.AllocateTransactionHandle: TSQLHandle;
  178. begin
  179. Result:=TMySQLTransaction.Create;
  180. end;
  181. procedure TMySQLConnection.PrepareStatement(cursor: TSQLCursor;
  182. ATransaction: TSQLTransaction; buf: string;AParams : TParams);
  183. begin
  184. if assigned(AParams) and (AParams.count > 0) then
  185. DatabaseError('Parameters (not) yet supported for the MySQL SqlDB connection.',self);
  186. With Cursor as TMysqlCursor do
  187. begin
  188. FStatement:=Buf;
  189. if FStatementType=stSelect then
  190. FNeedData:=True;
  191. ConnectMySQL(FQMySQL,FMySQL^.host,FMySQL^.user,FMySQL^.passwd);
  192. if mysql_select_db(FQMySQL,pchar(DatabaseName))<>0 then
  193. MySQLError(FQMySQL,SErrDatabaseSelectFailed,Self);
  194. end
  195. end;
  196. procedure TMySQLConnection.UnPrepareStatement(cursor: TSQLCursor);
  197. begin
  198. // not necessary
  199. end;
  200. procedure TMySQLConnection.FreeFldBuffers(cursor: TSQLCursor);
  201. Var
  202. C : TMySQLCursor;
  203. begin
  204. C:=Cursor as TMysqlCursor;
  205. if c.FStatementType=stSelect then
  206. c.FNeedData:=False;
  207. If (C.FRes<>Nil) then
  208. begin
  209. C.FRes:=Nil;
  210. end;
  211. if (c.FQMySQL <> Nil) then
  212. begin
  213. mysql_close(c.FQMySQL);
  214. c.FQMySQL:=Nil;
  215. end;
  216. If (C.FRes<>Nil) then
  217. begin
  218. Mysql_free_result(C.FRes);
  219. C.FRes:=Nil;
  220. end;
  221. end;
  222. procedure TMySQLConnection.Execute(cursor: TSQLCursor;
  223. atransaction: tSQLtransaction;AParams : TParams);
  224. Var
  225. C : TMySQLCursor;
  226. begin
  227. C:=Cursor as TMysqlCursor;
  228. If (C.FRes=Nil) then
  229. begin
  230. if mysql_query(c.FQMySQL,Pchar(C.FStatement))<>0 then
  231. MySQLError(c.FQMYSQL,Format(SErrExecuting,[StrPas(mysql_error(c.FQMySQL))]),Self)
  232. else
  233. begin
  234. C.RowsAffected := mysql_affected_rows(c.FQMYSQL);
  235. C.LastInsertID := mysql_insert_id(c.FQMYSQL);
  236. if C.FNeedData then
  237. C.FRes:=mysql_use_result(c.FQMySQL);
  238. end;
  239. end;
  240. end;
  241. function TMySQLConnection.MySQLDataType(AType: enum_field_types; ASize: Integer;
  242. var NewType: TFieldType; var NewSize: Integer): Boolean;
  243. begin
  244. Result := True;
  245. case AType of
  246. FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG, FIELD_TYPE_LONGLONG,
  247. FIELD_TYPE_INT24:
  248. begin
  249. NewType := ftInteger;
  250. NewSize := 0;
  251. end;
  252. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  253. begin
  254. NewType := ftFloat;
  255. NewSize := 0;
  256. end;
  257. FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  258. begin
  259. NewType := ftDateTime;
  260. NewSize := 0;
  261. end;
  262. FIELD_TYPE_DATE:
  263. begin
  264. NewType := ftDate;
  265. NewSize := 0;
  266. end;
  267. FIELD_TYPE_TIME:
  268. begin
  269. NewType := ftTime;
  270. NewSize := 0;
  271. end;
  272. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  273. begin
  274. NewType := ftString;
  275. NewSize := ASize;
  276. end;
  277. else
  278. Result := False;
  279. end;
  280. end;
  281. procedure TMySQLConnection.AddFieldDefs(cursor: TSQLCursor;
  282. FieldDefs: TfieldDefs);
  283. var
  284. C : TMySQLCursor;
  285. I, FC: Integer;
  286. field: PMYSQL_FIELD;
  287. DFT: TFieldType;
  288. DFS: Integer;
  289. begin
  290. // Writeln('MySQL: Adding fielddefs');
  291. C:=(Cursor as TMySQLCursor);
  292. If (C.FRes=Nil) then
  293. begin
  294. // Writeln('res is nil');
  295. MySQLError(c.FQMySQL,SErrNoQueryResult,Self);
  296. end;
  297. // Writeln('MySQL: have result');
  298. FC:=mysql_num_fields(C.FRes);
  299. For I:= 0 to FC-1 do
  300. begin
  301. field := mysql_fetch_field_direct(C.FRES, I);
  302. // Writeln('MySQL: creating fielddef ',I+1);
  303. if MySQLDataType(field^.ftype, field^.length, DFT, DFS) then
  304. TFieldDef.Create(FieldDefs, field^.name, DFT, DFS, False, I+1);
  305. end;
  306. // Writeln('MySQL: Finished adding fielddefs');
  307. end;
  308. function TMySQLConnection.Fetch(cursor: TSQLCursor): boolean;
  309. Var
  310. C : TMySQLCursor;
  311. begin
  312. C:=Cursor as TMySQLCursor;
  313. C.Row:=MySQL_Fetch_row(C.FRes);
  314. Result:=(C.Row<>Nil);
  315. end;
  316. function TMySQLConnection.LoadField(cursor : TSQLCursor;
  317. FieldDef : TfieldDef;buffer : pointer) : boolean;
  318. var
  319. I, FC, CT: Integer;
  320. field: PMYSQL_FIELD;
  321. row : TMYSQL_ROW;
  322. C : TMySQLCursor;
  323. begin
  324. // Writeln('LoadFieldsFromBuffer');
  325. C:=Cursor as TMySQLCursor;
  326. if C.Row=nil then
  327. begin
  328. // Writeln('LoadFieldsFromBuffer: row=nil');
  329. MySQLError(c.FQMySQL,SErrFetchingData,Self);
  330. end;
  331. Row:=C.Row;
  332. FC := mysql_num_fields(C.FRES);
  333. for I := 0 to FC-1 do
  334. begin
  335. field := mysql_fetch_field_direct(C.FRES, I);
  336. if field^.name=FieldDef.name then break;
  337. Inc(Row);
  338. end;
  339. CT := MySQLWriteData(field^.ftype, field^.length, Row^, Buffer);
  340. result := true;
  341. end;
  342. function InternalStrToFloat(S: string): Extended;
  343. var
  344. I: Integer;
  345. Tmp: string;
  346. begin
  347. Tmp := '';
  348. for I := 1 to Length(S) do
  349. begin
  350. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  351. Tmp := Tmp + DecimalSeparator
  352. else
  353. Tmp := Tmp + S[I];
  354. end;
  355. Result := StrToFloat(Tmp);
  356. end;
  357. function InternalStrToDate(S: string): TDateTime;
  358. var
  359. EY, EM, ED: Word;
  360. begin
  361. EY := StrToInt(Copy(S,1,4));
  362. EM := StrToInt(Copy(S,6,2));
  363. ED := StrToInt(Copy(S,9,2));
  364. if (EY = 0) or (EM = 0) or (ED = 0) then
  365. Result:=0
  366. else
  367. Result:=EncodeDate(EY, EM, ED);
  368. end;
  369. function InternalStrToDateTime(S: string): TDateTime;
  370. var
  371. EY, EM, ED: Word;
  372. EH, EN, ES: Word;
  373. begin
  374. EY := StrToInt(Copy(S, 1, 4));
  375. EM := StrToInt(Copy(S, 6, 2));
  376. ED := StrToInt(Copy(S, 9, 2));
  377. EH := StrToInt(Copy(S, 11, 2));
  378. EN := StrToInt(Copy(S, 14, 2));
  379. ES := StrToInt(Copy(S, 17, 2));
  380. if (EY = 0) or (EM = 0) or (ED = 0) then
  381. Result := 0
  382. else
  383. Result := EncodeDate(EY, EM, ED);
  384. Result := Result + EncodeTime(EH, EN, ES, 0);
  385. end;
  386. function InternalStrToTime(S: string): TDateTime;
  387. var
  388. EH, EM, ES: Word;
  389. begin
  390. EH := StrToInt(Copy(S, 1, 2));
  391. EM := StrToInt(Copy(S, 4, 2));
  392. ES := StrToInt(Copy(S, 7, 2));
  393. Result := EncodeTime(EH, EM, ES, 0);
  394. end;
  395. function InternalStrToTimeStamp(S: string): TDateTime;
  396. var
  397. EY, EM, ED: Word;
  398. EH, EN, ES: Word;
  399. begin
  400. EY := StrToInt(Copy(S, 1, 4));
  401. EM := StrToInt(Copy(S, 5, 2));
  402. ED := StrToInt(Copy(S, 7, 2));
  403. EH := StrToInt(Copy(S, 9, 2));
  404. EN := StrToInt(Copy(S, 11, 2));
  405. ES := StrToInt(Copy(S, 13, 2));
  406. if (EY = 0) or (EM = 0) or (ED = 0) then
  407. Result := 0
  408. else
  409. Result := EncodeDate(EY, EM, ED);
  410. Result := Result + EncodeTime(EH, EN, ES, 0);;
  411. end;
  412. function TMySQLConnection.MySQLWriteData(AType: enum_field_types;ASize: Integer; Source, Dest: PChar): Integer;
  413. var
  414. VI: Integer;
  415. VF: Double;
  416. VD: TDateTime;
  417. Src : String;
  418. begin
  419. Result := 0;
  420. If (Source<>Nil) Then
  421. Src:=StrPas(Source)
  422. else
  423. Src:='';
  424. case AType of
  425. FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG, FIELD_TYPE_LONGLONG,
  426. FIELD_TYPE_INT24:
  427. begin
  428. Result:=SizeOf(Integer);
  429. if (Src<>'') then
  430. VI := StrToInt(Src)
  431. else
  432. VI := 0;
  433. Move(VI, Dest^, Result);
  434. end;
  435. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  436. begin
  437. Result := SizeOf(Double);
  438. if Src <> '' then
  439. VF := InternalStrToFloat(Src)
  440. else
  441. VF := 0;
  442. Move(VF, Dest^, Result);
  443. end;
  444. FIELD_TYPE_TIMESTAMP:
  445. begin
  446. Result := SizeOf(TDateTime);
  447. if Src <> '' then
  448. VD := InternalStrToTimeStamp(Src)
  449. else
  450. VD := 0;
  451. Move(VD, Dest^, Result);
  452. end;
  453. FIELD_TYPE_DATETIME:
  454. begin
  455. Result := SizeOf(TDateTime);
  456. if Src <> '' then
  457. VD := InternalStrToDateTime(Src)
  458. else
  459. VD := 0;
  460. Move(VD, Dest^, Result);
  461. end;
  462. FIELD_TYPE_DATE:
  463. begin
  464. Result := SizeOf(TDateTime);
  465. if Src <> '' then
  466. VD := InternalStrToDate(Src)
  467. else
  468. VD := 0;
  469. Move(VD, Dest^, Result);
  470. end;
  471. FIELD_TYPE_TIME:
  472. begin
  473. Result := SizeOf(TDateTime);
  474. if Src <> '' then
  475. VD := InternalStrToTime(Src)
  476. else
  477. VD := 0;
  478. Move(VD, Dest^, Result);
  479. end;
  480. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  481. begin
  482. Result := ASize;
  483. { Write('Moving string of size ',asize,' : ');
  484. P:=Source;
  485. If (P<>nil) then
  486. While P[0]<>#0 do
  487. begin
  488. Write(p[0]);
  489. inc(p);
  490. end;
  491. Writeln;
  492. } if Src<> '' then
  493. Move(Source^, Dest^, Result)
  494. else
  495. Dest^ := #0;
  496. end;
  497. end;
  498. end;
  499. procedure TMySQLConnection.UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string);
  500. var qry : TSQLQuery;
  501. begin
  502. if not assigned(Transaction) then
  503. DatabaseError(SErrConnTransactionnSet);
  504. qry := tsqlquery.Create(nil);
  505. qry.transaction := Transaction;
  506. qry.database := Self;
  507. with qry do
  508. begin
  509. ReadOnly := True;
  510. sql.clear;
  511. sql.add('show index from ' + TableName);
  512. open;
  513. end;
  514. while not qry.eof do with IndexDefs.AddIndexDef do
  515. begin
  516. Name := trim(qry.fieldbyname('Key_name').asstring);
  517. Fields := trim(qry.fieldbyname('Column_name').asstring);
  518. If Name = 'PRIMARY' then options := options + [ixPrimary];
  519. If qry.fieldbyname('Non_unique').asinteger = 0 then options := options + [ixUnique];
  520. qry.next;
  521. { while (name = qry.fields[0].asstring) and (not qry.eof) do
  522. begin
  523. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  524. qry.next;
  525. end;}
  526. end;
  527. qry.close;
  528. qry.free;
  529. end;
  530. function TMySQLConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  531. begin
  532. Result:=Nil;
  533. end;
  534. function TMySQLConnection.Commit(trans: TSQLHandle): boolean;
  535. begin
  536. // Do nothing.
  537. end;
  538. function TMySQLConnection.RollBack(trans: TSQLHandle): boolean;
  539. begin
  540. // Do nothing
  541. end;
  542. function TMySQLConnection.StartdbTransaction(trans: TSQLHandle; AParams : string): boolean;
  543. begin
  544. // Do nothing
  545. end;
  546. procedure TMySQLConnection.CommitRetaining(trans: TSQLHandle);
  547. begin
  548. // Do nothing
  549. end;
  550. procedure TMySQLConnection.RollBackRetaining(trans: TSQLHandle);
  551. begin
  552. // Do nothing
  553. end;
  554. end.