Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Catalog · How the catalog works

Random project

delphi-orm

Delphi ORM

View on GitHub

Anyone may press Interesting, signed in or not. It helps others find this project.

Member rating

No ratings yet.

Sign in to rate this project.

README

delphi-orm

Поддерживает работу с MySQL и SQLite

Подкиньте в папку с проектом SchemaGenerator.exe. и в настройках проекта пропишите project-options-build events-prebuild events-command $(PROJECTDIR)\SchemaGenerator migration="$(PROJECTDIR)\Classes\DataBase\Migrations" , где "$(PROJECTDIR)\Classes\DataBase\Migrations" путь к файлам для миграций

Типы данных

pascal
procedure NewString(AName: string; ASize: integer = 255; ADefault: string = 'NULL');
procedure NewInteger(AName: string; ASize: integer = 11; ADefault: string = 'NULL');
procedure NewIntegerUnsigned(AName: string; ASize: integer = 11; ADefault: string = 'NULL');
procedure NewFloat(AName: string; ASize: integer = 16; ADecimalSize: integer = 2; ADefault: string = 'NULL');
procedure NewText(AName: string; ASize: integer = 65535; ADefault: string = 'NULL');
procedure NewBoolean(AName: string; ADefault: boolean = false);
procedure NewDateTime(AName: string; ADefault: string = 'NULL');
procedure NewDate(AName: string; ADefault: string = 'NULL');
procedure NewBlob(AName: string);
pascal
procedure NewTimestamps;

Пример миграции

pascal
unit migration_001_create_users_table;
pascal
interface
pascal
uses
  OlfeiSchema;
pascal
implementation
pascal
begin
  OlfeiTable := NewTable('users');
pascal
OlfeiTable.NewString('name'); 
OlfeiTable.NewString('password');
OlfeiTable.NewString('login');
OlfeiTable.NewTimestamps(); // Создает поля created_at и update_at
pascal
end.

Пример сида

pascal
unit migration_002_add_user_seed;
pascal
interface
pascal
uses
  OlfeiSchema;
pascal
implementation
pascal
begin
  OlfeiSeed := OlfeiTable.Seed;
pascal
OlfeiSeed.Values['login'] := 'admin';
OlfeiSeed.Values['password'] := '123';
OlfeiSeed.Values['name'] := 'Администратор';
pascal
end.

Пример модели

pascal
unit UserModel;
pascal
interface
pascal
uses
  OlfeiSQL, OlfeiORM;
pascal
type
  [TOlfeiTable('users')]
  TUserModel = class(TOlfeiORM)
    public
      [TOlfeiField('login')]
      property Login: String index 0 read GetString write SetString;
pascal
[TOlfeiField('password')]
property Password: String index 1 read GetString write SetString;
pascal
[TOlfeiField('name')]
property Name: String index 2 read GetString write SetString;
pascal
end;
pascal
implementation
pascal
end.

Пример коллекции

pascal
unit UserModel;
pascal
interface
pascal
uses
  OlfeiSQL, OlfeiCollection, UserModel;
pascal
type
  TUsersModels = class(TOlfeiCollection<TUserModel>)
    public
      constructor Create(FDB: TOlfeiDB); overload;
  end;
pascal
implementation
pascal
constructor TUsersModels.Create(FDB: TOlfeiDB);
begin
  inherited Create(FDB, TUserModel);
end;
pascal
end.

Пример модели со связанной коллекцией

pascal
[TOlfeiTable('users')]
TUserModel = class(TOlfeiORM)
    private
        function GetOlfeiImages(index: integer): TOlfeiCollection<TOlfeiImage>;
        function GetOlfeiFriends(index: integer): TOlfeiCollection<TUserModel>;
    public
        [TOlfeiField('login')]
        property Login: String index 0 read GetString write SetString;
pascal
[TOlfeiField('password')]
property Password: String index 1 read GetString write SetString;
pascal
[TOlfeiField('name')]
property Name: String index 2 read GetString write SetString;
pascal
[TOlfeiCollectionField('id', 'user_id')]
property Images: TOlfeiCollection<TOlfeiImage> index 0 read GetOlfeiImages;
pascal
[TOlfeiPivotField('user_friend', 'user_id', 'friend_id')]
property Friends: TOlfeiCollection<TUserModel> index 1 read GetOlfeiFriends;
pascal
end;
pascal
// Методы привязки
pascal
function TUserModel.GetOlfeiImages(index: Integer): TOlfeiCollection<TOlfeiImage>;
begin
  Result := TOlfeiCollection<TOlfeiImage>(Self.GetForeignCollection(index, TOlfeiImage));
end;
pascal
function TUserModel.GetOlfeiFriends(index: Integer): TOlfeiCollection<TUserModel>;
begin
  Result := TOlfeiCollection<TUserModel>(Self.GetPivotCollection(index, TUserModel));
end;

Работа с моделями и коллекциями

pascal
DB := InitDB; // Пример можно найти в Demo
Users := TUsersModels.Create(DB);
pascal
User := Users.Where('login', Login).Where('password', Pass).First;
Result := User.Exists;
pascal
User.Images; // Коллекция связанных изображений
for Image in User.Images do
    ShowMessage(Image.Path);
pascal
Users.Free; // Очищаем коллекцию, все связанные модели очистит сборщик мусора
DB.Free;

Обход данных

pascal
Users := TUsersModels.Create(DB);
for User in Users.All do
    ShowMessage(User.Name);

Удаление записи

pascal
User.Delete;

Очистка таблицы

pascal
Users.Truncate;

Методы для коллекций

pascal
.Where('field', 'value')
.Where('field', '=', 'value') // Тажке можно любое условие >, >=, <, <= и тд
.Where('field, 'IN', DB.Raw('(1, 2, 3)'))
.OrWhere('field', 'value')
.OrWhere('field', '=', 'value') // Тажке можно любое условие >, >=, <, <= и тд
.OrWhere('field, 'IN', DB.Raw('(1, 2, 3)'))
pascal
.OrderBy('field', 'ASC') // Можно также указать как DESC
pascal
.StartGroup
.StartAndGroup
.StartOrGroup
.EndGroup
pascal
.Join('table', 'remote_key', 'local_key')
.WhereFor('table', 'field', '=', 'value') // Тажке можно любое условие >, >=, <, <= и тд
.OrWhereFor('table', 'field', '=', 'value') // Тажке можно любое условие >, >=, <, <= и тд
.OrderByFor('table', 'field', 'ASC') // Можно также указать как DESC
pascal
.Limit('offset', 'limit')
.Count
.Sum('field')
.All
.First

Продолжение следует...