zrm/tests/relations.zig
Madeorsk 5a2964622c
Relations definition and SQL query build improvements.
+ Relations definition.
+ Add test submodels in testing database.
* Generalize raw SQL query preparation and build.
* Simplify and improve SQL query build algorithms.
2024-11-22 15:41:05 +01:00

54 lines
1.5 KiB
Zig

const std = @import("std");
const pg = @import("pg");
const zrm = @import("zrm");
const repository = @import("repository.zig");
/// PostgreSQL database connection.
var database: *pg.Pool = undefined;
/// Initialize database connection.
fn initDatabase(allocator: std.mem.Allocator) !void {
database = try pg.Pool.init(allocator, .{
.connect = .{
.host = "localhost",
.port = 5432,
},
.auth = .{
.username = "zrm",
.password = "zrm",
.database = "zrm",
},
.size = 1,
});
}
test "belongsTo" {
zrm.setDebug(true);
try initDatabase(std.testing.allocator);
defer database.deinit();
var poolConnector = zrm.database.PoolConnector{
.pool = database,
};
// Build a query of submodels.
var myQuery = repository.MySubmodelRepository.Query.init(std.testing.allocator, poolConnector.connector(), .{});
defer myQuery.deinit();
// Retrieve parents of submodels from relation.
try myQuery.with(repository.MySubmodelRelations.parent);
try myQuery.buildSql();
// Get query result.
var result = try myQuery.get(std.testing.allocator);
defer result.deinit();
// Checking result.
try std.testing.expectEqual(2, result.models.len);
try std.testing.expectEqual(1, result.models[0].parent_id);
try std.testing.expectEqual(1, result.models[1].parent_id);
try std.testing.expectEqual(repository.MyModel, @TypeOf(result.models[0].parent.?));
try std.testing.expectEqual(repository.MyModel, @TypeOf(result.models[1].parent.?));
try std.testing.expectEqual(1, result.models[0].parent.?.id);
try std.testing.expectEqual(1, result.models[1].parent.?.id);
}