One-to-one relationships with raw SQL queries
When designing a database, the tables we define often relate to each other. Managing those relationships is one of the essential parts of working with…
September 5, 2022
When designing a database, the tables we define often relate to each other. Managing those relationships is one of the essential parts of working with databases. Building on the basics of using raw SQL queries with NestJS and PostgreSQL, this article goes a step further and starts writing more complex SQL queries involving the one-to-one relationship.
You can find the code from this article in this repository.
The idea behind one-to-one relationship#
When designing a one-to-one relationship, a row from the first table has one matching row from the second table and the other way around.
In our case, the address is optional. A one-to-one relationship that is optional might be also referred to as one-to-zero-or-one relationship.
Instead of creating the addresses table, we could add the address_street, address_city, and address_country to the users table. However, as the table grows, it might sometimes make sense to split it into more than one table if we can separate a particular group of columns. This might not be the most popular type of relationship, but we might encounter it when working with various databases. Because of that, we go through how to set it up and work with it.
When deciding on whether to create a one-to-one relationship we can take a lot of factors into consideration. If you want to read more, check out this question on StackOverflow.
Working with a one-to-one relationship#
A very straightforward example involves a user and an address. Let’s start by creating a new migration to define the addresses table and connect it to the users.
20220831115100_add_addresses_table.ts#
import { Knex } from "knex"
export async function up(knex: Knex): Promise<void> {
return knex.raw(`
CREATE TABLE addresses (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
street text,
city text,
country text
);
ALTER TABLE users
ADD COLUMN address_id int UNIQUE REFERENCES addresses(id);
`)
}
export async function down(knex: Knex): Promise<void> {
return knex.raw(`
DROP TABLE addresses;
ALTER TABLE users
DROP COLUMN address_id;
`)
}Above, we add the address_id column to the users table. In our application, a particular address can belong only to one user. Because of that, we add the unique constraint to the address_id column. When we do that, we ensure that only one user can refer to a particular address. Trying to tie more than one user to the same address would result in an error.
We also make the address_id column a foreign key that refers to the primary key of the addresses table. Thanks to that, we make sure that PostgreSQL knows there is a connection.
Inserting two entities in a single query#
We want to be able to insert the user and the address into the database at the same time. A good way to do that is by using the WITH statement.
users.repository.ts#
import { Injectable } from "@nestjs/common"
import DatabaseService from "../database/database.service"
import { plainToInstance } from "class-transformer"
import UserModel from "./user.model"
import { CreateUserDto } from "./dto/createUser.dto"
import isRecord from "../utils/isRecord"
import PostgresErrorCode from "../database/postgresErrorCode.enum"
import UserAlreadyExistsException from "./exceptions/userAlreadyExists.exception"
@Injectable()
class UsersRepository {
constructor(private readonly databaseService: DatabaseService) {}
private async createUserWithAddress(userData: CreateUserDto) {
try {
const databaseResponse = await this.databaseService.runQuery(
`
WITH created_address AS (
INSERT INTO addresses (
street,
city,
country
) VALUES (
$1,
$2,
$3
) RETURNING *
)
INSERT INTO users (
email,
name,
password,
address_id
) VALUES (
$4,
$5,
$6,
(SELECT id FROM created_address)
) RETURNING *
`,
[
userData.address.street,
userData.address.city,
userData.address.country,
userData.email,
userData.name,
userData.password,
],
)
return new UserModel(databaseResponse.rows[0])
} catch (error) {
if (isRecord(error) && error.code === PostgresErrorCode.UniqueViolation) {
throw new UserAlreadyExistsException(userData.email)
}
throw error
}
}
async create(userData: CreateUserDto) {
if (userData.address) {
return this.createUserWithAddress(userData)
} // ...
} // ...
}
export default UsersRepositoryAbove, we create a Common Table Expression query using the WITH statement. Thanks to that, we create both the address and the user in a single SQL that is atomic. If something goes wrong when creating the user, the address won’t be persisted in the database.
Expanding the models#
As our queries get more complex, the models grow bigger too. So let’s first create a model for the address.
address.model.ts#
interface AddressModelData {
id: number
street: string
city: string
country: string
}
class AddressModel {
id: number
street: string
city: string
country: string
constructor(data: AddressModelData) {
this.id = data.id
this.street = data.street
this.city = data.city
this.country = data.country
}
}
export default AddressModelAbove, I create the model and define the constructor manually. You can use the class-transformer library for that, if you prefer.
The last step in creating the models is to use the above class in the model of the user.
user.model.ts#
import { Exclude } from "class-transformer"
import AddressModel from "./address.model"
type UserModelData = {
id: number
name: number
email: string
password: string
address_id?: number
address_street?: string
address_city?: string
address_country?: string
}
class UserModel {
id: number
name: number
email: string
@Exclude()
password: string
address?: AddressModel
constructor(data: UserModelData) {
this.id = data.id
this.name = data.name
this.email = data.email
this.password = data.password
if (data.address_id) {
this.address = new AddressModel({
id: data.address_id,
street: data.address_street,
city: data.address_city,
country: data.address_country,
})
}
}
}
export default UserModelQuerying two tables#
Our queries can fetch rows from multiple tables at once and match them. A good way of doing that is with a JOIN query.
SELECT users.*,
addresses.street as address_street, addresses.city as address_city, addresses.country as address_country
FROM users
JOIN addresses ON users.address_id = addresses.id
WHERE email=$1When we use the JOIN keyword, we perform the inner join. The crucial thing is that it returns records with matching values in both tables. In our case, the address is optional. Running the above query for a user that does not have the address would return nothing.
To fix the issue, we need to perform the outer join. Outer joins preserve the rows that don’t have matching values. In our case, we want to use the LEFT JOIN that returns all records from the left table and the matched records from the right table. In our case, the left table is users, and the right table is the addresses.
users.repository.ts#
import { Injectable, NotFoundException } from "@nestjs/common"
import DatabaseService from "../database/database.service"
import UserModel from "./user.model"
@Injectable()
class UsersRepository {
constructor(private readonly databaseService: DatabaseService) {}
async getByEmail(email: string) {
const databaseResponse = await this.databaseService.runQuery(
`
SELECT users.*,
addresses.street as address_street, addresses.city as address_city, addresses.country as address_country
FROM users
LEFT JOIN addresses ON users.address_id = addresses.id
WHERE email=$1
`,
[email],
)
const entity = databaseResponse.rows[0]
if (!entity) {
throw new NotFoundException()
}
return new UserModel(entity)
}
}
export default UsersRepositoryThanks to the above approach, our query works correctly for users that don’t have the address.
Returning the related entity when inserting#
Before, we used the WITH statement to create the user and the address in a single query. We can use two WITH statements to return the data from both tables.
users.repository.ts#
import { Injectable } from "@nestjs/common"
import DatabaseService from "../database/database.service"
import UserModel from "./user.model"
import { CreateUserDto } from "./dto/createUser.dto"
import isRecord from "../utils/isRecord"
import PostgresErrorCode from "../database/postgresErrorCode.enum"
import UserAlreadyExistsException from "./exceptions/userAlreadyExists.exception"
@Injectable()
class UsersRepository {
constructor(private readonly databaseService: DatabaseService) {}
private async createUserWithAddress(userData: CreateUserDto) {
try {
const databaseResponse = await this.databaseService.runQuery(
`
WITH created_address AS (
INSERT INTO addresses (
street,
city,
country
) VALUES (
$1,
$2,
$3
) RETURNING *
),
created_user AS (
INSERT INTO users (
email,
name,
password,
address_id
) VALUES (
$4,
$5,
$6,
(SELECT id FROM created_address)
) RETURNING *
)
SELECT created_user.id AS id, created_user.email AS email, created_user.name AS name, created_user.password AS password,
created_address.id AS address_id, street AS address_street, city AS address_city, country AS address_country
FROM created_user, created_address
`,
[
userData.address.street,
userData.address.city,
userData.address.country,
userData.email,
userData.name,
userData.password,
],
)
return new UserModel(databaseResponse.rows[0])
} catch (error) {
if (isRecord(error) && error.code === PostgresErrorCode.UniqueViolation) {
throw new UserAlreadyExistsException(userData.email)
}
throw error
}
} // ...
}
export default UsersRepositoryThanks to the above, our API returns the user together with the address when signing up.
Summary#
In this article, we’ve gone through the idea behind one-to-one relationships. We’ve also learned to work with them using PostgreSQL and raw SQL queries. When doing that, we had to write common table expressions to make sure we created two entities in a single query. We’ve also identified the difference between inner and outer joins. There is still much to learn regarding relationships in PostgreSQL, so stay tuned!