Password hash column
Learn how to add a nullable password_hash column to the users table with a migration and keep the Rust User struct in step
The password_hash column is the one place in the database where a password lives, and it never holds a password. It holds the Argon2 hash string for the user: one text value, 97 characters long, that proves the person knew the password without ever recording what the password was. Adding the column is a one line migration, and the interesting part is not the line itself. It is why the column is nullable, why it is plain text, and why the Rust struct the API returns does not gain a field for it.
Where This Fits
The users table already exists with four columns: an id, a name, an email, and a timestamp. The hashing tool from the previous page produces one string per password, and that string needs a home. This page gives it one. A new column is added to the existing table, the old rows stay exactly as they are, and the handlers that read and write users learn which columns they may touch and which they must leave alone.
Think of a paper register that gains a new column ruled down the side. The old entries keep their values, the new column starts blank for them, and only new entries fill it in. The register is still the same register, and the clerk still reads the same columns as before, plus one more when the job calls for it.
The Smallest Working Version
The change is a migration, a versioned SQL file that alters the schema in one step. Create the file with the migration command, run from the project root:
cargo sqlx migrate add add_password_hash_column
Creating migrations/20261114075822_add_password_hash_column.sql
The command prints one line and creates one empty file. The file name has two parts. 20261114075822 is the version, a timestamp in the form year, month, day, hour, minute, second. add_password_hash_column is the description, written with underscores. The version decides the order, so this file runs after the migration that created the users table, because its timestamp is later.
Replace the placeholder comment inside the new file with the one statement:
ALTER TABLE users ADD COLUMN password_hash TEXT;
ALTER TABLE is the SQL command that changes the shape of an existing table instead of creating a new one. ADD COLUMN says a column is being added. password_hash is the column name, and TEXT is its type, the Postgres type for text of any length. There is no NOT NULL on the line, and that absence is deliberate. The next section explains why.
Apply the pending migration:
cargo sqlx migrate run
Applied 20261114075822/migrate add password hash column (97.278011ms)
The output names the version, the direction (migrate, meaning forward), the description with spaces, and the time the migration took. Check the state:
cargo sqlx migrate info
20261114075821/installed create users table
20261114075822/installed add password hash column
Both lines say installed, which means both migrations have run. Run the same run command a second time, and it prints nothing and succeeds, because there is nothing pending. That silence is the guarantee that migrations run once.
Working Setup:
If migrate info shows both migrations as installed, and the describe command below shows a fifth column named password_hash, the column exists. Nothing else needs to exist first, and the old rows are untouched.
Checking the Table After the Migration
The describe command, \d users, prints the table as Postgres sees it:
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "\d users"
Table "public.users"
Column | Type | Collation | Nullable | Default
---------------+--------------------------+-----------+----------+-----------------------------------
id | integer | | not null | nextval('users_id_seq'::regclass)
name | text | | not null |
email | text | | not null |
created_at | timestamp with time zone | | not null | now()
password_hash | text | | |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"users_email_key" UNIQUE CONSTRAINT, btree (email)
Five columns now, and the new one is the only column with an empty Nullable entry that is not marked not null. The Default entry is empty too, which means an INSERT that does not name the column leaves it null. Null is SQL's way of saying "no value", and it is the value every existing row holds for this column right now, because those rows were written before the column existed.
The same change can be made by hand, without a migration file, by running the statement directly:
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "ALTER TABLE users ADD COLUMN password_hash TEXT;"
ALTER TABLE
The direct command is useful for trying the change out, and the migration file is what keeps the change. A table altered by hand exists on one machine only, while the file travels with the project and rebuilds the same table on every machine that runs the migrations. Use the direct command to learn, and the file to keep.
Why the Column Is Nullable
A new column on a table that already has rows must answer one question: what value do the old rows get? A NOT NULL column with no default has no answer, and Postgres refuses the statement. The failure is easy to see on a small test table with one row already in it:
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "ALTER TABLE probe ADD COLUMN secret TEXT NOT NULL;"
ERROR: column "secret" of relation "probe" contains null values
The error is Postgres saying the existing row would need a value it does not have. A nullable column has an answer: the old rows get null. That is exactly what this column needs, because the old rows were created before passwords existed in this app, and inventing a hash for them would be lying. A null hash is honest. It says this user has no password stored, and the login check treats it as a failed check, which is the correct behaviour for an account that was never given a password.
A NOT NULL column can still be added to a populated table when a default value is supplied, like ADD COLUMN nickname TEXT NOT NULL DEFAULT ''. That fills the old rows with the default and requires a value for future rows. It is the wrong shape here, because an empty string is not a valid password hash, and a login check that found an empty string would have to treat it as a failure anyway. Null already means "no value", so it says the same thing without pretending an empty string is a hash.
New rows written by the signup handler always supply a hash, so in practice only the old rows stay null. The column is nullable for the old rows, not for the new ones, and the handler is what keeps the new ones honest.
Null Means No Password, Not an Empty Password:
A null hash and an empty string hash are different values with different meanings, and only one of them is honest. Null means the user has no password on file, and the login check answers 401. An empty string means a hash was stored that is not a hash, and the login check has to handle a damaged value. Store a real hash or store nothing, and let null carry the nothing.
Why TEXT and Not a Fixed Length
The PHC string is 97 characters long with the default settings: the algorithm, version, settings, a 16 byte salt, and a 32 byte hash output, all in base64 text with dollar signs between the fields. A column type with a fixed size limit, like VARCHAR(97), would hold today's string and break the day the settings change. Raising the memory cost changes nothing about the length, but a longer salt or a longer output would, and a future version of the crate could produce a longer string for the same reason. TEXT holds any length, so the column never needs to change when the hash format grows, and the handler checks the shape of the value instead of the column enforcing a guessed size.
The same reasoning applies to the other text columns in this table. The name and the email are TEXT for the same reason. A size limit is a guess about real data, and guesses about data the app does not control are usually wrong. Validation in the handler is where a length rule belongs, because the error message there can explain it, and the column stays out of the way.
What the Column Holds and What It Never Holds
The column holds exactly one kind of value: a PHC string produced by Argon2, starting with $argon2id$v=19$. It never holds a plain password, it never holds a fast hash like a SHA-256 digest, and it never holds a hash that was cut short by a column limit. A row written by the signup handler looks like this when read back:
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "SELECT id, name, email, left(password_hash, 30) AS hash_start, length(password_hash) AS hash_len FROM users;"
id | name | email | hash_start | hash_len
----+------+------------------+--------------------------------+----------
1 | Asha | asha@example.com | $argon2id$v=19$m=19456,t=2,p=1 | 97
The left(password_hash, 30) call shows only the first 30 characters, which is enough to confirm the algorithm, version, and settings without printing the whole hash into a terminal history. The length is 97, which matches the PHC string from the hashing page. A row whose hash is shorter than that, or does not start with $argon2id$, was not written by this app, and the login check will treat it as a damaged value.
Reading the full hash out of the table by hand is possible, and it is also pointless. The string cannot be turned back into a password, and printing it into a terminal or a log file spreads a sensitive value for no benefit. Check the prefix and the length when debugging, and leave the full string in the table.
Never Put a Plain Password in This Column:
The column is named password_hash, and the name is a rule, not a suggestion. An INSERT that writes the typed password into it compiles, runs, and silently creates the exact failure the hashing page warned about, with a column name that claims otherwise. If a row ever shows a readable password in this column, the fix is to hash it at signup, re-hash every affected account by asking those users to reset, and check the handler code that wrote it.
The Rust Struct Stays in Step
The User struct the API returns does not change. It holds the id, the name, and the email, and nothing else, because the API never returns a password hash to a client.
#[derive(Debug, Serialize, FromRow)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
}
The rule is the same one the table page established: a struct holds only what the client needs, and every SELECT lists exactly the columns the struct has. The INSERT in the signup handler names the new column, because it writes the hash, but its RETURNING list names only the three columns of User:
INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email
The write list and the read list are different on purpose. The write list has four columns, because the row needs a hash stored. The read list has three, because the response must not carry one. If the RETURNING list asked for password_hash as well, the compile time check would fail, because User has no field to hold it, and the error would name the extra column. That failure is the check doing its job.
The login check does need to read the column, and it reads it into a second struct, one that exists only inside the server and is never sent to a client:
#[derive(Debug, FromRow)]
pub struct StoredUser {
pub id: i32,
pub name: String,
pub email: String,
pub password_hash: Option<String>,
}
Three things about this struct deserve attention. First, it derives FromRow but not Serialize, because it is never turned into JSON. A struct that cannot be serialised cannot leak into a response by accident. Second, its SELECT lists all four columns, including the hash, because that is the whole point of the struct. Third, the hash field is Option<String>, not String, because the column is nullable. Option is Rust's way of saying a value may be absent, and a null in the database becomes None in Rust, while a real hash becomes Some with the string inside. A struct that declared the field as a plain String would fail to decode every old row, because sqlx has no string to put in it for a null, and the login check would return a 500 for a table that looks fine.
The two structs side by side are the whole relationship between the table and the code:
| Table column | Postgres type | User field | StoredUser field | Sent to the client |
|---|---|---|---|---|
id | SERIAL PRIMARY KEY | id: i32 | id: i32 | Yes |
name | TEXT NOT NULL | name: String | name: String | Yes |
email | TEXT NOT NULL UNIQUE | email: String | email: String | Yes |
created_at | TIMESTAMPTZ NOT NULL DEFAULT NOW() | - | - | No |
password_hash | TEXT | - | password_hash: Option<String> | No |
Two columns never cross into a response. created_at stays in the table for the people running the system, and password_hash stays inside the server for the login check. The column list in each query is the boundary between the table and the client, and writing the columns out, instead of SELECT *, keeps that boundary honest.
What a Null Hash Means for Login
A null hash means the user cannot log in with a password. There is no password on file to check against, so any password the person types is the wrong one, and the login check answers with the same generic 401 it gives for a wrong password. The row below is a user created directly in the database, without a password, and it shows the null plainly:
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "SELECT id, name, email, password_hash FROM users WHERE email = 'nopass@example.com';"
id | name | email | password_hash
----+-------+--------------------+---------------
2 | NoPass | nopass@example.com |
The empty cell at the end is the null. The account exists, the name and email are real, and the password column holds nothing. That account can only log in if a password is set for it later, by writing a hash into the column. Until then, the login check sees None, stops there, and answers 401, without ever running Argon2. The check does not distinguish this case from a wrong password in its answer, and that sameness is the subject of the login check page.
Count how many users have no password with one query, which is useful after a migration on a table that already had rows:
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "SELECT COUNT(*) FROM users WHERE password_hash IS NULL;"
count
-------
1
IS NULL is the SQL test for a null value, and it is the only correct test for one. The = operator never matches null, because null is not a value that equals anything, not even another null. A query written as password_hash = NULL returns no rows at all, which is a classic beginner mistake in SQL, and it is worth learning here, because this column is the first nullable column in the table.
The Migration Steps in Order
Adding a column to a live table is a short sequence, and the order matters. Each step depends on the one before it.
Step 1: Create the migration file
Run cargo sqlx migrate add add_password_hash_column from the project root. The command creates an empty file with a timestamp version that sorts after the table creation migration.
cargo sqlx migrate add add_password_hash_column
Step 2: Write the ALTER TABLE statement
Replace the placeholder comment in the new file with the single statement. The column is nullable, so existing rows get null and the statement succeeds on a populated table.
ALTER TABLE users ADD COLUMN password_hash TEXT;
Step 3: Apply the migration
Run cargo sqlx migrate run with DATABASE_URL set. The command applies only the pending files, in version order, and records the new one in the tracking table.
cargo sqlx migrate run
Step 4: Confirm with describe and info
Run cargo sqlx migrate info and \d users. The first shows the migration as installed, and the second shows the fifth column with no not null marker.
cargo sqlx migrate info
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "\d users"
Skipping step 2 and running an empty migration does nothing, and the tracking table records an empty change, which is worse than doing nothing, because the history then claims a change happened that did not. Skipping step 4 leaves the change unverified, and the first sign of trouble would be a handler failing at runtime instead of a describe command showing the missing column now.
Common Beginner Mistakes
Adding the column as NOT NULL on a populated table
-- Wrong - the existing rows have no value for the new column, and Postgres refuses
ALTER TABLE users ADD COLUMN password_hash TEXT NOT NULL;
The error names the problem directly: column "password_hash" of relation "users" contains null values. The fix is the nullable column on this page. A NOT NULL column is only safe on an empty table, or with a default that fills the old rows, and an empty string is not a valid hash to fill them with. Keep the column nullable, and let the signup handler supply a real hash for new rows.
Editing the applied migration to add the column
-- Wrong - the table creation migration already ran, and editing it changes its checksum
-- migrations/20261114075821_create_users_table.sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
password_hash TEXT
);
An applied migration is frozen history. Editing it changes its checksum, and the next migration run fails on every machine that already applied it, with the error that the migration was previously applied but has been modified. The fix is a new migration, exactly as this page does. The old file stays as it was, and the history records both the table creation and the column addition, in order, which is honest and readable.
Adding the hash to the User struct
// Wrong - the hash would travel into every API response
#[derive(Debug, Serialize, FromRow)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
pub password_hash: Option<String>,
}
This compiles, and that is what makes it dangerous. The struct derives Serialize, so every handler that returns a User would send the hash to the client in the JSON body, and the hash is a sensitive value that the client never needs. The fix is the split on this page. User stays at three fields and is the only struct that becomes JSON, and StoredUser holds the hash, derives no Serialize, and is used only inside the login check.
Sizing the column for a different hash
-- Wrong - 60 characters fits a bcrypt hash, and an Argon2 PHC string is 97
ALTER TABLE users ADD COLUMN password_hash VARCHAR(60);
The number 60 comes from bcrypt, a different password hashing function whose output is 60 characters long. An Argon2 PHC string is 97 characters with the default settings, so a VARCHAR(60) column would cut the string short, and the stored value would fail to parse at login. The failure would look like a broken login for every user, and the cause would be a column type chosen from the wrong algorithm's documentation. TEXT has no length limit, so it holds the string whatever its length, and the handler checks the format instead.
A Truncated Hash Fails Every Login:
A hash that was cut short by a column limit is not a wrong password, it is a damaged stored value, and the login check answers 500 for it, not 401. If logins start failing for every user at once after a schema change, check the length of the stored strings before anything else. The fix is the column type on this page, plus re-hashing the affected accounts.
Final Complete Example
Here is everything from this page in one place: the two migration files, the table as Postgres sees it, and the two structs with their column lists.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE users ADD COLUMN password_hash TEXT;
use serde::Serialize;
use sqlx::FromRow;
#[derive(Debug, Serialize, FromRow)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
}
#[derive(Debug, FromRow)]
pub struct StoredUser {
pub id: i32,
pub name: String,
pub email: String,
pub password_hash: Option<String>,
}
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "\d users"
Table "public.users"
Column | Type | Collation | Nullable | Default
---------------+--------------------------+-----------+----------+-----------------------------------
id | integer | | not null | nextval('users_id_seq'::regclass)
name | text | | not null |
email | text | | not null |
created_at | timestamp with time zone | | not null | now()
password_hash | text | | |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"users_email_key" UNIQUE CONSTRAINT, btree (email)
Run the migrations in order, and the table grows from four columns to five, the old rows keep their values with null in the new column, and the two structs agree with the table by construction. The signup handler writes the hash, the login check reads it, and the API response carries neither.
Summary
The column is one line of SQL, and the decisions around that line are the page. Nullable, because the old rows have no password and honesty beats an invented default. Plain text, because the hash string is self describing and its length is not a promise. Held in a struct that never becomes JSON, because the hash is a server secret, not a client field. The question to ask when the next column arrives is the same set, in the same order: what do the existing rows get, who writes it, who reads it, and does the client ever see it. When the answers are null, the signup handler, the login check, and nobody, the column is shaped right, and the table is ready for the handlers that use it.