Blog App Tutorial Part 2

Part 2 creates users and their profiles.

Create one user

ballerina
type UserRow record {
    int id;
    string email;
    string name;
    string status;
};

UserRow thambaru = check (check db.'from(User).create({
    email: "hi@thambaru.com",
    name: "Thambaru",
    status: ACTIVE
})).cloneWithType();

Create many users

ballerina
UserRow[] users = check (check db.'from(User).createMany([
    {email: "kasun@example.com", name: "Kasun Perera", status: ACTIVE},
    {email: "nadeesha@example.com", name: "Nadeesha Fernando", status: ACTIVE},
    {email: "chathura@example.com", name: "Chathura Silva", status: INACTIVE}
])).cloneWithType();

Create profile (ONE_TO_ONE)

ballerina
type UserProfileRow record {
    int id;
    int userId;
    string? bio;
    string? website;
    string? location;
};

UserProfileRow _ = check (check db.'from(UserProfile).create({
    userId: thambaru.id,
    bio: "Software engineer passionate about distributed systems",
    website: "https://thambaru.com",
    location: "Sri Lanka"
})).cloneWithType();

Query users with filters

ballerina
UserRow[] activeUsers = check (check db.'from(User)
    .'where({status: {'equals: ACTIVE}})
    .orderBy({email: orm:ASC})
    .findMany()).cloneWithType();

UserRow[] exampleUsers = check (check db.'from(User)
    .'where({email: {contains: "@example.com"}})
    .findMany()).cloneWithType();

Load profile separately

ballerina
record {}? userRow = check db.'from(User)
    .'where({email: {'equals: "hi@thambaru.com"}})
    .findUnique();

if userRow is record {} {
    UserRow user = check userRow.cloneWithType();

    record {}? profileRow = check db.'from(UserProfile)
        .'where({userId: {'equals: user.id}})
        .findFirst();

    if profileRow is record {} {
        UserProfileRow profile = check profileRow.cloneWithType();
        // use profile
        _ = profile;
    }
}

Next step

Proceed to Part 3: Posts & Comments.