-
MY PROJECTS
-
Recent Posts
- SQL.How can you compare two nullable values safely, and how does IS DISTINCT FROM differ from <>?
- SQL.How are NULL values ordered by ORDER BY, how do defaults differ between databases, and how can you control their placement?
- SQL.How does NULL propagate through arithmetic expressions, and how can COALESCE and NULLIF help handle missing values and division by zero?
- SQL.How does NULL affect join conditions, and why can filtering the right-hand table in WHERE remove unmatched rows from a LEFT JOIN?
- SQL.How do GROUP BY and DISTINCT treat NULL values, even though NULL = NULL evaluates to UNKNOWN?
- SQL.How do aggregate functions handle NULL, and what is the difference between COUNT(*), COUNT(column), and COUNT(DISTINCT column)?
- SQL.How does NULL affect IN and NOT IN, and why can NOT EXISTS be a safer choice when a subquery returns nullable values?
- SQL.How do WHERE, HAVING, and CHECK constraints treat conditions that evaluate to UNKNOWN?
- SQL.Why do column = NULL and column <> NULL not work as expected, and when should you use IS NULL and IS NOT NULL?
- SQL.What is SQL’s three-valued logic (TRUE, FALSE, UNKNOWN), and how do AND, OR, and NOT behave with UNKNOWN?
- ChromeDevTools.Watch all failed requests
- SQL.What are domain types (or constraints on data types), and how do they help enforce data correctness?
- SQL.How does SQL handle comparisons between different data types (for example, string vs number), and why is this dangerous?
- SQL.What is the difference between DATE, TIME, TIMESTAMP, and TIMESTAMPTZ, and which one should be used for business events?
- SQL.How do numeric types like INTEGER, BIGINT, DECIMAL, and FLOAT differ in terms of precision and use cases?
- SQL.What problems can arise from implicit type casting in SQL, and how can it affect indexes?
- SQL.How does NULL differ from 0, an empty string, or FALSE in SQL?
- SQL.What is the difference between CHAR, VARCHAR, and TEXT, and when would you choose each?
- SQL.What is MVCC ?
- SQL.What is AutoVacuum Postgres ?
Categories
- Aptana
- Azure
- C#
- DataSnap
- DBExpress
- Delphi
- Delphi и сети
- Delphi. Язык программирования
- ExtJS
- FastReport
- FireDAC
- FireMonkey
- GIT
- ICS
- IDE
- IIS
- Indy
- InnoSetup
- javascript
- jQuery
- JSON
- LiveBindings
- MSHTML
- MySQL
- PHP
- REST
- Ribbons
- SMS
- SQL инструкции
- SVN
- TRichView
- UniGui
- WebBroker
- WinAPI
- Windows
- Алгоритмы
- Без рубрики
- Деревья
- Ищу ответ
- Компонентостроение
- Мои компоненты
- Начальный уровень
- Обработка исключений
- Парсинг
- Потоки(Threads)
- Регулярные выражения
- Тестирование приложений
Category Archives: Delphi
Delphi.RobustServer.Упрощаем routing запросов. Базовый класс TRP
Дописал базовый класс TRP, от которого можно наследовать всю бизнес логику. Теперь можно обращаться, скажем по адресу Users/Create, сервер найдет класс TRPUsers и попытается найти у него метод Create. Реализация TRP включает в себя RTTI механизм. Чуть позже есть идея … Continue reading
Posted in Delphi
Comments Off on Delphi.RobustServer.Упрощаем routing запросов. Базовый класс TRP
Delphi.RobustServer.Обработка POST запросов для основных MIME
Доработал обработку POST запросов для следующих MIME типов application/json application/x-www-form-urlencoded multipart/form-data Теперь сервер умеет работать с json, принимать файлы, пока ещё не оч. большие (poststream блоками читается в строку = оперативную память), поэтому по-хорошему, размер файлов надо ограничить, ну и … Continue reading
Posted in Delphi
Comments Off on Delphi.RobustServer.Обработка POST запросов для основных MIME
Delphi.RobustServer. Логгер на GUI
Добавил логгер на GUI Механизм такой – при добавлении сообщения в лог, автоматически обновляется GUI. Сообщения идут в обратном порядке. Ключевым моментом является функция WaitAndCreateLogFileStream класса TLDSLogger. Сначала сообщения пишутся в файл, затем из файла в GUI. Всей многопоточной логикой заведует … Continue reading
Posted in Delphi
Comments Off on Delphi.RobustServer. Логгер на GUI
Delphi.RobustServer.Открытие соединения с БД.Простой случай.
Как и когда нужно создавать экземпляр соединения с бд в серверном приложении? Путем чтения книг, опыта и ошибок я понял, что под каждый запрос, создается поток, под каждый поток нужно создавать соединение отдельно, иначе начинается хаос… Но это в случае, если … Continue reading
Posted in Delphi
Comments Off on Delphi.RobustServer.Открытие соединения с БД.Простой случай.
Delphi.RobustServer. Загрузка файлов на сервер
Сделал простую загрузку файлов на сервер, с возможностью создания уникального имени, если такое имя уже будет в директории сервера. Сама директория будет строиться как files/year/month/day Результат кода выглядит так Сам запрос идет через multipart следующим образом…
Posted in Delphi
Comments Off on Delphi.RobustServer. Загрузка файлов на сервер
Delphi.RobustServer. Совершенствуем CommandGet и тестовый класс TRPUsers
Немного отрефакторил код OnCommandGet, получилось так, довольно коротко…
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var r: IResponses; begin r := TResponses.Create(ARequestInfo, AResponseInfo); try ProcessTests(ARequestInfo, AResponseInfo); ProcessUsers(ARequestInfo, AResponseInfo); AResponseInfo.ResponseNo := 404; except on E: Exception do r.Error(e.Message); end; end; |
Обработка запросов происходит в методах Process…, например ProcessUsers выглядит так
Posted in Delphi
Comments Off on Delphi.RobustServer. Совершенствуем CommandGet и тестовый класс TRPUsers
Delphi.RobustServer.Обработка ошибок, интерфейсный класс TResponses и измерение оперативной памяти
Сделал обработку ошибок следующим образом В модуле CommandGet сделал единый блок try / except
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
procedure TCommandGet.Execute(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var json: ISuperObject; r: IResponses; d, a, b: Double; begin r := TResponses.Create(ARequestInfo, AResponseInfo); try if ARequestInfo.URI = '/testConnection' then r.OK() else if ARequestInfo.URI = '/testException' then begin a := 1; b := 0; d := a / b; end else AResponseInfo.ResponseNo := 404; except on E: Exception do r.Error(e.Message); end; end; |
Теперь, если возникнет ошибка при обработке запроса, она не потеряется, а придет в понятном json формате, то есть вот так…. Кстати, здесь же можно посмотреть, … Continue reading
Posted in Delphi
Comments Off on Delphi.RobustServer.Обработка ошибок, интерфейсный класс TResponses и измерение оперативной памяти
Delphi. Измерение оперативной памяти
Модуль из проекта Вот эти 2 процедуры измеряют текущую память и пиковую
|
1 2 |
class function CurrentProcessMemoryKB: Extended; static; class function CurrentProcessMemoryPeakKB: Extended; static; |
Полный модуль
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
unit uRPMemory; interface uses System.SysUtils, System.Classes, IdContext, IdCustomHTTPServer; type TRPMemory = class(TDataModule) private { Private declarations } class function CurrentProcessMemoryKB: Extended; static; class function CurrentProcessMemoryPeakKB: Extended; static; public { Public declarations } class procedure GetMemory(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); static; end; implementation uses Winapi.PsAPI, Winapi.Windows, Math; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} class function TRPMemory.CurrentProcessMemoryKB: Extended; var MemCounters: TProcessMemoryCounters; begin MemCounters.cb := SizeOf(MemCounters); if GetProcessMemoryInfo(GetCurrentProcess, @MemCounters, SizeOf(MemCounters)) then Result := trunc(MemCounters.WorkingSetSize / 1024) else RaiseLastOSError; end; class function TRPMemory.CurrentProcessMemoryPeakKB: Extended; var MemCounters: TProcessMemoryCounters; begin MemCounters.cb := SizeOf(MemCounters); if GetProcessMemoryInfo(GetCurrentProcess, @MemCounters, SizeOf(MemCounters)) then Result := trunc(MemCounters.PeakWorkingSetSize / 1024) else RaiseLastOSError; end; class procedure TRPMemory.GetMemory(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var curr, peak: Extended; begin curr := Math.RoundTo(CurrentProcessMemoryKB / 1024, -2); peak := Math.RoundTo(CurrentProcessMemoryPeakKB / 1024, -2); AResponseInfo.ResponseNo := 200; AResponseInfo.ContentType := 'application/json'; AResponseInfo.CacheControl := 'no-cache'; AResponseInfo.CustomHeaders.Add('Access-Control-Allow-Origin: *'); AResponseInfo.ContentText := curr.ToString + ' / ' + peak.ToString + ' (MB)'; AResponseInfo.WriteContent; end; end. |
Posted in Delphi
Comments Off on Delphi. Измерение оперативной памяти
Delphi.RobustServer – первые шаги
Github Первые несколько шагов. Текущую версию я делаю Visual Components Library App. Потом можно будет перевернуть это приложение в сервис, при желании. Архитектура следующая
Posted in Delphi
Comments Off on Delphi.RobustServer – первые шаги
Delphi. RobustServer. Пишем мощный и надежный сервер на Indy
На мой взгляд, более менее универсальная архитектура приложения выглядит так… В этом и последующем постах будем писать мощный и надежный сервер. Это будет шаблон для будущих проектов. Стэк технологий у нас будет следующий Delphi Seattle MySQL FireDAC SuperObject … Ближайшие … Continue reading
Posted in Delphi
Comments Off on Delphi. RobustServer. Пишем мощный и надежный сервер на Indy