source: trunk/Packages/Database/USqlDatabase.pas

Last change on this file was 26, checked in by chronos, 21 months ago
  • Removed: TemplateGenerics as required package. Used Generics.Collections instead.
File size: 13.7 KB
Line 
1unit USqlDatabase;
2
3// Modified: 2022-09-08
4
5interface
6
7uses
8 SysUtils, Classes, Dialogs, mysql50, TypInfo, UGenerics, Generics.Collections;
9
10type
11 EQueryError = class(Exception);
12
13 TClientCapabilities = (_CLIENT_LONG_PASSWORD, _CLIENT_FOUND_ROWS,
14 _CLIENT_LONG_FLAG, _CLIENT_CONNECT_WITH_DB, _CLIENT_NO_SCHEMA,
15 _CLIENT_COMPRESS, _CLIENT_ODBC, _CLIENT_LOCAL_FILES, _CLIENT_IGNORE_SPACE,
16 _CLIENT_INTERACTIVE, _CLIENT_SSL, _CLIENT_IGNORE_SIGPIPE, _CLIENT_TRANSACTIONS);
17
18 TSetClientCapabilities = set of TClientCapabilities;
19
20 TLogEvent = procedure(Sender: TObject; Text: string) of object;
21
22 TDbRows = class(TList<TDictionaryStringString>)
23 private
24 function GetData(Index: Integer): TDictionaryStringString;
25 procedure SetData(Index: Integer; const Value: TDictionaryStringString);
26 public
27 property Data[Index: Integer]: TDictionaryStringString read GetData write SetData; default;
28 destructor Destroy; override;
29 end;
30
31 { TSqlDatabase }
32
33 TSqlDatabase = class(TComponent)
34 private
35 FEncoding: string;
36 FHostName: string;
37 FPassword: string;
38 FPort: Word;
39 FSession: PMYSQL;
40 FConnected: Boolean;
41 FDatabase: string;
42 FUserName: string;
43 FOnLogQuery: TLogEvent;
44 procedure mySQLClient1ConnectError(Sender: TObject; Msg: String);
45 function GetConnected: Boolean;
46 function GetLastErrorMessage: string;
47 function GetLastErrorNumber: Integer;
48 function GetCharset: string;
49 procedure SetConnected(const AValue: Boolean);
50 procedure SetDatabase(const Value: string);
51 procedure SetEncoding(AValue: string);
52 public
53 LastUsedTable: string;
54 LastQuery: string;
55 function EscapeString(Text: string): string;
56 procedure CreateDatabase;
57 procedure CreateTable(Name: string);
58 procedure CreateColumn(Table, ColumnName: string; ColumnType: TTypeKind);
59 procedure Query(DbRows: TDbRows; Data: string);
60 procedure Select(DbRows: TDbRows; ATable: string; Filter: string = '*';
61 Condition: string = '');
62 procedure Delete(ATable: string; Condition: string = '';
63 Schema: string = '');
64 procedure Insert(ATable: string; Data: TDictionaryStringString;
65 Schema: string = '');
66 procedure Update(ATable: string; Data: TDictionaryStringString;
67 Condition: string = ''; Schema: string = '');
68 procedure Replace(ATable: string; Data: TDictionaryStringString;
69 Schema: string = '');
70 procedure Connect;
71 procedure Disconnect;
72 function LastInsertId: Integer;
73 property LastErrorMessage: string read GetLastErrorMessage;
74 property LastErrorNumber: Integer read GetLastErrorNumber;
75 constructor Create(AOwner: TComponent); override;
76 destructor Destroy; override;
77 property Charset: string read GetCharset;
78 published
79 property Connected: Boolean read GetConnected write SetConnected;
80 property Database: string read FDatabase write SetDatabase;
81 property HostName: string read FHostName write FHostName;
82 property UserName: string read FUserName write FUserName;
83 property Password: string read FPassword write FPassword;
84 property Port: Word read FPort write FPort;
85 property Encoding: string read FEncoding write SetEncoding;
86 property OnLogQuery: TLogEvent read FOnLogQuery write FOnLogQuery;
87 end;
88
89 function MySQLFloatToStr(F: Real): string;
90 function MySQLStrToFloat(S: string): Real;
91 function SQLToDateTime(Value: string): TDateTime;
92 function DateTimeToSQL(Value: TDateTime): string;
93
94procedure Register;
95
96
97implementation
98
99uses
100 DateUtils;
101
102resourcestring
103 SDatabaseQueryError = 'Database query error: "%s"';
104
105const
106 CLIENT_LONG_PASSWORD = 1; // new more secure passwords
107 CLIENT_FOUND_ROWS = 2; // Found instead of affected rows
108 CLIENT_LONG_FLAG = 4; // Get all column flags
109 CLIENT_CONNECT_WITH_DB = 8; // One can specify db on connect
110 CLIENT_NO_SCHEMA = 16; // Don't allow database.table.column
111 CLIENT_COMPRESS = 32; // Can use compression protcol
112 CLIENT_ODBC = 64; // Odbc client
113 CLIENT_LOCAL_FILES = 128; // Can use LOAD DATA LOCAL
114 CLIENT_IGNORE_SPACE = 256; // Ignore spaces before '('
115 CLIENT_INTERACTIVE = 1024; // This is an interactive client
116 CLIENT_SSL = 2048; // Switch to SSL after handshake
117 CLIENT_IGNORE_SIGPIPE = 4096; // IGNORE sigpipes
118 CLIENT_TRANSACTIONS = 8192; // Client knows about transactions
119
120procedure Register;
121begin
122 RegisterComponents('CoolWeb', [TSqlDatabase]);
123end;
124
125function MySQLFloatToStr(F: Real): string;
126var
127 S: string;
128begin
129 S := FloatToStr(F);
130 if Pos(',', S) > 0 then S[Pos(',', S)] := '.';
131 Result := S;
132end;
133
134function MySQLStrToFloat(S: string): Real;
135begin
136 if Pos('.', S) > 0 then S[Pos('.', S)] := ',';
137 Result := StrToFloat(S);
138end;
139
140function StrToStr(Value: string): string;
141begin
142 Result := Value;
143end;
144
145function SQLToDateTime(Value: string): TDateTime;
146var
147 Parts: TListString;
148 DateParts: TListString;
149 TimeParts: TListString;
150begin
151 try
152 Parts := TListString.Create;
153 DateParts := TListString.Create;
154 TimeParts := TListString.Create;
155
156 Parts.Explode(' ', Value);
157 DateParts.Explode('-', Parts[0]);
158 Result := EncodeDate(StrToInt(DateParts[0]), StrToInt(DateParts[1]),
159 StrToInt(DateParts[2]));
160 if Parts.Count > 1 then begin
161 TimeParts.Explode(':', Parts[1]);
162 Result := Result + EncodeTime(StrToInt(TimeParts[0]), StrToInt(TimeParts[1]),
163 StrToInt(TimeParts[2]), 0);
164 end;
165 finally
166 DateParts.Free;
167 TimeParts.Free;
168 Parts.Free;
169 end;
170end;
171
172function DateTimeToSQL(Value: TDateTime): string;
173begin
174 Result := FormatDateTime('yyyy-mm-dd hh.nn.ss', Value);
175end;
176
177{ TSqlDatabase }
178
179procedure TSqlDatabase.Connect;
180var
181 NewSession: PMYSQL;
182 Rows: TDbRows;
183begin
184 FSession := mysql_init(FSession);
185 NewSession := mysql_real_connect(FSession, PChar(HostName), PChar(UserName),
186 PChar(Password), PChar(Database), FPort, nil, CLIENT_LONG_PASSWORD + CLIENT_CONNECT_WITH_DB);
187 if Assigned(NewSession) then begin
188 FConnected := True;
189 FSession := NewSession;
190 end else FConnected := False;
191
192 if LastErrorNumber <> 0 then
193 raise EQueryError.Create(Format(SDatabaseQueryError, [LastErrorMessage]));
194
195 try
196 Rows := TDbRows.Create;
197 Query(Rows, 'SET NAMES ' + FEncoding);
198 finally
199 Rows.Free;
200 end;
201end;
202
203procedure TSqlDatabase.Insert(ATable: string; Data: TDictionaryStringString;
204 Schema: string);
205var
206 DbNames: string;
207 DbValues: string;
208 I: Integer;
209 Value: string;
210 DbResult: TDbRows;
211 Item: TPair<string, string>;
212begin
213 LastUsedTable := ATable;
214 DbNames := '';
215 DbValues := '';
216 for Item in Data do begin
217 Value := Item.Value;
218 StringReplace(Value, '"', '\"', [rfReplaceAll]);
219 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
220 else DbValues := DbValues + ',"' + Value + '"';
221 DbNames := DbNames + ',`' + Item.Key + '`';
222 end;
223 System.Delete(DbNames, 1, 1);
224 System.Delete(DbValues, 1, 1);
225 try
226 DbResult := TDbRows.Create;
227 if Schema <> '' then Schema := '`' + Schema + '`.';
228 Query(DbResult, 'INSERT INTO ' + Schema + '`' + ATable + '` (' + DbNames + ') VALUES (' + DbValues + ')');
229 finally
230 DbResult.Free;
231 end;
232end;
233
234procedure TSqlDatabase.Query(DbRows: TDbRows; Data: string);
235var
236 I, II: Integer;
237 DbResult: PMYSQL_RES;
238 DbRow: MYSQL_ROW;
239begin
240 DbRows.Clear;
241 if Assigned(FOnLogQuery) then FOnLogQuery(Self, Data);
242 LastQuery := Data;
243 mysql_query(FSession, PChar(Data));
244 if LastErrorNumber <> 0 then begin
245 raise EQueryError.Create(Format(SDatabaseQueryError, [LastErrorMessage]));
246 end;
247
248 DbResult := mysql_store_result(FSession);
249 try
250 if Assigned(DbResult) then begin
251 DbRows.Count := mysql_num_rows(DbResult);
252 for I := 0 to DbRows.Count - 1 do begin
253 DbRow := mysql_fetch_row(DbResult);
254 DbRows[I] := TDictionaryStringString.Create;
255 with DbRows[I] do begin
256 for II := 0 to mysql_num_fields(DbResult) - 1 do begin
257 Add(mysql_fetch_field_direct(DbResult, II)^.Name,
258 PChar((DbRow + II)^));
259 end;
260 end;
261 end;
262 end;
263 finally
264 mysql_free_result(DbResult);
265 end;
266end;
267
268procedure TSqlDatabase.Replace(ATable: string; Data: TDictionaryStringString;
269 Schema: string = '');
270var
271 DbNames: string;
272 DbValues: string;
273 Value: string;
274 I: Integer;
275 DbResult: TDbRows;
276 Item: TPair<string, string>;
277begin
278 LastUsedTable := ATable;
279 DbNames := '';
280 DbValues := '';
281 for Item in Data do begin
282 Value := Item.Value;
283 StringReplace(Value, '"', '\"', [rfReplaceAll]);
284 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
285 else DbValues := DbValues + ',"' + Value + '"';
286 DbNames := DbNames + ',`' + Item.Key + '`';
287 end;
288 System.Delete(DbNames, 1, 1);
289 System.Delete(DbValues, 1, 1);
290 try
291 DbResult := TDbRows.Create;
292 if Schema <> '' then Schema := '`' + Schema + '`.';
293 Query(DbResult, 'REPLACE INTO ' + Schema + '`' + ATable + '` (' + DbNames + ') VALUES (' + DbValues + ')');
294 finally
295 DbResult.Free;
296 end;
297end;
298
299procedure TSqlDatabase.Select(DbRows: TDbRows; ATable: string; Filter: string = '*'; Condition: string = '');
300var
301 QueryText: string;
302begin
303 LastUsedTable := ATable;
304 QueryText := 'SELECT ' + Filter + ' FROM `' + ATable + '`';
305 if Condition <> '' then QueryText := QueryText + ' WHERE ' + Condition;
306 Query(DbRows, QueryText);
307end;
308
309procedure TSqlDatabase.Update(ATable: string; Data: TDictionaryStringString;
310 Condition: string = ''; Schema: string = '');
311var
312 QueryText: string;
313 DbValues: string;
314 Value: string;
315 I: Integer;
316 DbResult: TDbRows;
317 Item: TPair<string, string>;
318begin
319 LastUsedTable := ATable;
320 DbValues := '';
321 for Item in Data do begin
322 Value := Item.Value;
323 StringReplace(Value, '"', '\"', [rfReplaceAll]);
324 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
325 else DbValues := DbValues + ',`' + Item.Key + '` =' + '"' + Value + '"';
326 end;
327 System.Delete(DbValues, 1, 1);
328 try
329 DbResult := TDbRows.Create;
330 if Schema <> '' then Schema := '`' + Schema + '`.';
331 QueryText := 'UPDATE ' + Schema + '`' + ATable + '` SET ' + DbValues;
332 if Condition <> '' then QueryText := QueryText + ' WHERE ' + Condition;
333 Query(DbResult, QueryText);
334 finally
335 DbResult.Free;
336 end;
337end;
338
339procedure TSqlDatabase.mySQLClient1ConnectError(Sender: TObject; Msg: String);
340begin
341// LastError := Msg + '('+IntToStr(mySQLClient1.LastErrorNumber)+')';
342end;
343
344procedure TSqlDatabase.Delete(ATable: string; Condition: string = '';
345 Schema: string = '');
346var
347 QueryText: string;
348 DbResult: TDbRows;
349begin
350 LastUsedTable := ATable;
351 try
352 DbResult := TDbRows.Create;
353 if Schema <> '' then Schema := '`' + Schema + '`.';
354 QueryText := 'DELETE FROM ' + Schema + '`' + ATable + '`';
355 if Condition <> '' then QueryText := QueryText + ' WHERE ' + Condition;
356 Query(DbResult, QueryText);
357 finally
358 DbResult.Free;
359 end;
360end;
361
362function TSqlDatabase.GetConnected: Boolean;
363begin
364 Result := FConnected;
365end;
366
367procedure TSqlDatabase.Disconnect;
368begin
369 mysql_close(FSession);
370 FConnected := False;
371end;
372
373constructor TSqlDatabase.Create(AOwner: TComponent);
374begin
375 inherited;
376 FSession := nil;
377 Encoding := 'utf8';
378 FPort := 3306;
379end;
380
381function TSqlDatabase.LastInsertId: Integer;
382begin
383 Result := mysql_insert_id(FSession);
384end;
385
386function TSqlDatabase.GetLastErrorMessage: string;
387begin
388 Result := mysql_error(FSession);
389end;
390
391function TSqlDatabase.GetLastErrorNumber: Integer;
392begin
393 Result := mysql_errno(FSession);
394end;
395
396procedure TSqlDatabase.CreateDatabase;
397var
398 TempDatabase: string;
399 DbRows: TDbRows;
400begin
401 TempDatabase := Database;
402 Database := 'mysql';
403 Connect;
404 try
405 DbRows := TDbRows.Create;
406 Query(DbRows, 'CREATE DATABASE ' + TempDatabase);
407 finally
408 DbRows.Free;
409 end;
410 Disconnect;
411 Database := TempDatabase;
412end;
413
414procedure TSqlDatabase.CreateTable(Name: string);
415var
416 DbRows: TDbRows;
417begin
418 try
419 DbRows := TDbRows.Create;
420 Query(DbRows, 'CREATE TABLE `' + Name + '`' +
421 ' (`Id` INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (`Id`));');
422 finally
423 DbRows.Free;
424 end;
425end;
426
427procedure TSqlDatabase.CreateColumn(Table, ColumnName: string;
428 ColumnType: TTypeKind);
429const
430 ColTypes: array[0..17] of string = ('', 'INT', 'CHAR', 'INT', 'DOUBLE',
431 'VARCHAR(255)', 'SET', 'INT', '', '', 'TEXT', 'TEXT', '', '', '', '', '', '');
432var
433 DbRows: TDbRows;
434begin
435 try
436 DbRows := TDbRows.Create;
437 Query(DbRows, 'ALTER TABLE `' + Table + '` ADD `' + ColumnName + '` ' +
438 ColTypes[Integer(ColumnType)] + ' NOT NULL');
439 finally
440 DbRows.Free;
441 end;
442end;
443
444destructor TSqlDatabase.Destroy;
445begin
446 if Connected then Disconnect;
447end;
448
449function TSqlDatabase.GetCharset: string;
450begin
451 Result := mysql_character_set_name(FSession);
452end;
453
454procedure TSqlDatabase.SetConnected(const AValue: Boolean);
455begin
456 if AValue = FConnected then Exit;
457 if AValue then Connect
458 else Disconnect;
459end;
460
461procedure TSqlDatabase.SetDatabase(const Value: string);
462begin
463 FDatabase := Value;
464 if FConnected then mysql_select_db(FSession, PChar(FDatabase));
465end;
466
467procedure TSqlDatabase.SetEncoding(AValue: string);
468var
469 Rows: TDbRows;
470begin
471 if FEncoding = AValue then Exit;
472 FEncoding := AValue;
473 if Connected then begin
474 try
475 Rows := TDbRows.Create;
476 Query(Rows, 'SET NAMES ' + FEncoding);
477 finally
478 Rows.Free;
479 end;
480 end;
481end;
482
483function TSqlDatabase.EscapeString(Text: string): string;
484var
485 L: Integer;
486begin
487 SetLength(Result, Length(Text) * 2 + 1);
488 L := mysql_real_escape_string(FSession, PChar(Result), PChar(Text), Length(Text));
489 SetLength(Result, L);
490end;
491
492{ TDbRows }
493
494destructor TDbRows.Destroy;
495begin
496 inherited;
497end;
498
499function TDbRows.GetData(Index: Integer): TDictionaryStringString;
500begin
501 Result := TDictionaryStringString(Items[Index]);
502end;
503
504procedure TDbRows.SetData(Index: Integer; const Value: TDictionaryStringString);
505begin
506 Items[Index] := Value;
507end;
508
509end.
510
Note: See TracBrowser for help on using the repository browser.