Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplifying timestamps #38

Open
oliverjam opened this issue Oct 15, 2021 · 0 comments
Open

Simplifying timestamps #38

oliverjam opened this issue Oct 15, 2021 · 0 comments

Comments

@oliverjam
Copy link

function createPost(id, textContent) {
const INSERT_POST = `INSERT INTO posts (user_id, text_content, created_at) VALUES ($1, $2, (SELECT CURRENT_TIMESTAMP))`;
return db.query(INSERT_POST, [id, textContent]);
}

Good idea to put a created_at column in your posts table. You will usually regret not doing this later on 😅

You could avoid the need to specify the timestamp manually on each insert by using a SQL "default" when you set the table up:

CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    text_content TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Then you just don't specify that column on insert—Postgres will automatically use the default value.

(If you really want to type less apparently now() will give the same result as current_timestamp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant