source: trunk/Packages/CoolWeb/Persistence/SqlDatabase.pas

Last change on this file was 151, checked in by chronos, 8 months ago
  • Property svn:executable set to *
File size: 13.6 KB
Line 
1unit SqlDatabase;
2
3// Modified: 2022-09-08
4
5interface
6
7uses
8 SysUtils, Classes, Dialogs, mysql50, TypInfo, Generics, 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 Value: string;
209 DbResult: TDbRows;
210 Item: TPair<string, string>;
211begin
212 LastUsedTable := ATable;
213 DbNames := '';
214 DbValues := '';
215 for Item in Data do begin
216 Value := Item.Value;
217 StringReplace(Value, '"', '\"', [rfReplaceAll]);
218 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
219 else DbValues := DbValues + ',"' + Value + '"';
220 DbNames := DbNames + ',`' + Item.Key + '`';
221 end;
222 System.Delete(DbNames, 1, 1);
223 System.Delete(DbValues, 1, 1);
224 try
225 DbResult := TDbRows.Create;
226 if Schema <> '' then Schema := '`' + Schema + '`.';
227 Query(DbResult, 'INSERT INTO ' + Schema + '`' + ATable + '` (' + DbNames + ') VALUES (' + DbValues + ')');
228 finally
229 DbResult.Free;
230 end;
231end;
232
233procedure TSqlDatabase.Query(DbRows: TDbRows; Data: string);
234var
235 I, II: Integer;
236 DbResult: PMYSQL_RES;
237 DbRow: MYSQL_ROW;
238begin
239 DbRows.Clear;
240 if Assigned(FOnLogQuery) then FOnLogQuery(Self, Data);
241 LastQuery := Data;
242 mysql_query(FSession, PChar(Data));
243 if LastErrorNumber <> 0 then begin
244 raise EQueryError.Create(Format(SDatabaseQueryError, [LastErrorMessage]));
245 end;
246
247 DbResult := mysql_store_result(FSession);
248 try
249 if Assigned(DbResult) then begin
250 DbRows.Count := mysql_num_rows(DbResult);
251 for I := 0 to DbRows.Count - 1 do begin
252 DbRow := mysql_fetch_row(DbResult);
253 DbRows[I] := TDictionaryStringString.Create;
254 with DbRows[I] do begin
255 for II := 0 to mysql_num_fields(DbResult) - 1 do begin
256 Add(mysql_fetch_field_direct(DbResult, II)^.Name,
257 PChar((DbRow + II)^));
258 end;
259 end;
260 end;
261 end;
262 finally
263 mysql_free_result(DbResult);
264 end;
265end;
266
267procedure TSqlDatabase.Replace(ATable: string; Data: TDictionaryStringString;
268 Schema: string = '');
269var
270 DbNames: string;
271 DbValues: string;
272 Value: string;
273 DbResult: TDbRows;
274 Item: TPair<string, string>;
275begin
276 LastUsedTable := ATable;
277 DbNames := '';
278 DbValues := '';
279 for Item in Data do begin
280 Value := Item.Value;
281 StringReplace(Value, '"', '\"', [rfReplaceAll]);
282 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
283 else DbValues := DbValues + ',"' + Value + '"';
284 DbNames := DbNames + ',`' + Item.Key + '`';
285 end;
286 System.Delete(DbNames, 1, 1);
287 System.Delete(DbValues, 1, 1);
288 try
289 DbResult := TDbRows.Create;
290 if Schema <> '' then Schema := '`' + Schema + '`.';
291 Query(DbResult, 'REPLACE INTO ' + Schema + '`' + ATable + '` (' + DbNames + ') VALUES (' + DbValues + ')');
292 finally
293 DbResult.Free;
294 end;
295end;
296
297procedure TSqlDatabase.Select(DbRows: TDbRows; ATable: string; Filter: string = '*'; Condition: string = '');
298var
299 QueryText: string;
300begin
301 LastUsedTable := ATable;
302 QueryText := 'SELECT ' + Filter + ' FROM `' + ATable + '`';
303 if Condition <> '' then QueryText := QueryText + ' WHERE ' + Condition;
304 Query(DbRows, QueryText);
305end;
306
307procedure TSqlDatabase.Update(ATable: string; Data: TDictionaryStringString;
308 Condition: string = ''; Schema: string = '');
309var
310 QueryText: string;
311 DbValues: string;
312 Value: string;
313 DbResult: TDbRows;
314 Item: TPair<string, string>;
315begin
316 LastUsedTable := ATable;
317 DbValues := '';
318 for Item in Data do begin
319 Value := Item.Value;
320 StringReplace(Value, '"', '\"', [rfReplaceAll]);
321 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
322 else DbValues := DbValues + ',`' + Item.Key + '` =' + '"' + Value + '"';
323 end;
324 System.Delete(DbValues, 1, 1);
325 try
326 DbResult := TDbRows.Create;
327 if Schema <> '' then Schema := '`' + Schema + '`.';
328 QueryText := 'UPDATE ' + Schema + '`' + ATable + '` SET ' + DbValues;
329 if Condition <> '' then QueryText := QueryText + ' WHERE ' + Condition;
330 Query(DbResult, QueryText);
331 finally
332 DbResult.Free;
333 end;
334end;
335
336procedure TSqlDatabase.mySQLClient1ConnectError(Sender: TObject; Msg: String);
337begin
338// LastError := Msg + '('+IntToStr(mySQLClient1.LastErrorNumber)+')';
339end;
340
341procedure TSqlDatabase.Delete(ATable: string; Condition: string = '';
342 Schema: string = '');
343var
344 QueryText: string;
345 DbResult: TDbRows;
346begin
347 LastUsedTable := ATable;
348 try
349 DbResult := TDbRows.Create;
350 if Schema <> '' then Schema := '`' + Schema + '`.';
351 QueryText := 'DELETE FROM ' + Schema + '`' + ATable + '`';
352 if Condition <> '' then QueryText := QueryText + ' WHERE ' + Condition;
353 Query(DbResult, QueryText);
354 finally
355 DbResult.Free;
356 end;
357end;
358
359function TSqlDatabase.GetConnected: Boolean;
360begin
361 Result := FConnected;
362end;
363
364procedure TSqlDatabase.Disconnect;
365begin
366 mysql_close(FSession);
367 FConnected := False;
368end;
369
370constructor TSqlDatabase.Create(AOwner: TComponent);
371begin
372 inherited;
373 FSession := nil;
374 Encoding := 'utf8';
375 FPort := 3306;
376end;
377
378function TSqlDatabase.LastInsertId: Integer;
379begin
380 Result := mysql_insert_id(FSession);
381end;
382
383function TSqlDatabase.GetLastErrorMessage: string;
384begin
385 Result := mysql_error(FSession);
386end;
387
388function TSqlDatabase.GetLastErrorNumber: Integer;
389begin
390 Result := mysql_errno(FSession);
391end;
392
393procedure TSqlDatabase.CreateDatabase;
394var
395 TempDatabase: string;
396 DbRows: TDbRows;
397begin
398 TempDatabase := Database;
399 Database := 'mysql';
400 Connect;
401 try
402 DbRows := TDbRows.Create;
403 Query(DbRows, 'CREATE DATABASE ' + TempDatabase);
404 finally
405 DbRows.Free;
406 end;
407 Disconnect;
408 Database := TempDatabase;
409end;
410
411procedure TSqlDatabase.CreateTable(Name: string);
412var
413 DbRows: TDbRows;
414begin
415 try
416 DbRows := TDbRows.Create;
417 Query(DbRows, 'CREATE TABLE `' + Name + '`' +
418 ' (`Id` INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (`Id`));');
419 finally
420 DbRows.Free;
421 end;
422end;
423
424procedure TSqlDatabase.CreateColumn(Table, ColumnName: string;
425 ColumnType: TTypeKind);
426const
427 ColTypes: array[0..17] of string = ('', 'INT', 'CHAR', 'INT', 'DOUBLE',
428 'VARCHAR(255)', 'SET', 'INT', '', '', 'TEXT', 'TEXT', '', '', '', '', '', '');
429var
430 DbRows: TDbRows;
431begin
432 try
433 DbRows := TDbRows.Create;
434 Query(DbRows, 'ALTER TABLE `' + Table + '` ADD `' + ColumnName + '` ' +
435 ColTypes[Integer(ColumnType)] + ' NOT NULL');
436 finally
437 DbRows.Free;
438 end;
439end;
440
441destructor TSqlDatabase.Destroy;
442begin
443 if Connected then Disconnect;
444end;
445
446function TSqlDatabase.GetCharset: string;
447begin
448 Result := mysql_character_set_name(FSession);
449end;
450
451procedure TSqlDatabase.SetConnected(const AValue: Boolean);
452begin
453 if AValue = FConnected then Exit;
454 if AValue then Connect
455 else Disconnect;
456end;
457
458procedure TSqlDatabase.SetDatabase(const Value: string);
459begin
460 FDatabase := Value;
461 if FConnected then mysql_select_db(FSession, PChar(FDatabase));
462end;
463
464procedure TSqlDatabase.SetEncoding(AValue: string);
465var
466 Rows: TDbRows;
467begin
468 if FEncoding = AValue then Exit;
469 FEncoding := AValue;
470 if Connected then begin
471 try
472 Rows := TDbRows.Create;
473 Query(Rows, 'SET NAMES ' + FEncoding);
474 finally
475 Rows.Free;
476 end;
477 end;
478end;
479
480function TSqlDatabase.EscapeString(Text: string): string;
481var
482 L: Integer;
483begin
484 SetLength(Result, Length(Text) * 2 + 1);
485 L := mysql_real_escape_string(FSession, PChar(Result), PChar(Text), Length(Text));
486 SetLength(Result, L);
487end;
488
489{ TDbRows }
490
491destructor TDbRows.Destroy;
492begin
493 inherited;
494end;
495
496function TDbRows.GetData(Index: Integer): TDictionaryStringString;
497begin
498 Result := TDictionaryStringString(Items[Index]);
499end;
500
501procedure TDbRows.SetData(Index: Integer; const Value: TDictionaryStringString);
502begin
503 Items[Index] := Value;
504end;
505
506end.
507
Note: See TracBrowser for help on using the repository browser.