1656128181
In this tutorial, we will show how to create a little complex table association or relationship with CRUD (Create, Read, Update, Delete) operations. A comprehensive step by step tutorial on building REST API using Node.js, Express.js, Sequelize.js, and PostgreSQL.
The following tools, frameworks, and modules are required for this tutorial:
We assume that you have installed the PostgreSQL server in your machine or can use your own remote server (we are using PostgreSQL 9.5.13). Also, you have installed Node.js on your machine and can run `node`, `npm`, or `yarn` command in your terminal or command line. Next, check their version by type these commands in your terminal or command line.
node -v
v8.11.1
npm -v
6.1.0
yarn -v
1.7.0
Open your terminal or node command line the go to your projects folder. First, install express-generator using this command.
sudo npm install express-generator -g
Next, create an Express.js app using this command.
express node-sequelize --view=ejs
This will create Express.js project with the EJS view instead of the Jade view template because using '--view=ejs' parameter. Next, go to the newly created project folder then install node modules.
cd node-sequelize && npm install
You should see the folder structure like this.
There's no view yet using the latest Express generator. We don't need it because we will create a RESTful API.
Before installing the modules for this project, first, install Sequelize-CLI by type this command.
sudo npm install -g sequelize-cli
To install the Sequelize.js module, type this command.
npm install --save sequelize
Then install the module for PostgreSQL.
npm install --save pg pg-hstore
Next, create a new file at the root of the project folder that initializes the Sequelize configuration.
touch .sequelizerc
Open and edit that file then add these lines of codes.
const path = require('path');
module.exports = {
"config": path.resolve('./config', 'config.json'),
"models-path": path.resolve('./models'),
"seeders-path": path.resolve('./seeders'),
"migrations-path": path.resolve('./migrations')
};
That files will tell Sequelize initialization to generate config, models, seeders, and migrations files to specific directories. Next, type this command to initialize the Sequelize.
sequelize init
That command will create `config/config.json`, `models/index.js`, `migrations`, and `seeders` directories and files. Next, open and edit `config/config.json` then make it like this.
{
"development": {
"username": "codequs",
"password": "codequs12",
"database": "node_sequelize",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "root",
"password": "codequs12",
"database": "node_sequelize",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"username": "root",
"password": "codequs12",
"database": "node_sequelize",
"host": "127.0.0.1",
"dialect": "postgres"
}
}
We use the same configuration for all the environment because we are using the same machine, server, and database for this tutorial.
Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.
psql postgres --u postgres
Next, type this command for creating a new user with a password then give access for creating the database.
postgres-# CREATE ROLE djamware WITH LOGIN PASSWORD 'codequs12';
postgres-# ALTER ROLE codequs CREATEDB;
Quit `psql` then log in again using the new user that previously created.
postgres-# \q
psql postgres -U codequs
Enter the password, then you will enter this `psql` console.
psql (9.5.13)
Type "help" for help.
postgres=>
Type this command to creating a new database.
postgres=> CREATE DATABASE node_sequelize;
Then give that new user privileges to the new database then quit the `psql`.
postgres=> GRANT ALL PRIVILEGES ON DATABASE node_sequelize TO codequs;
postgres=> \q
We will use Sequelize-CLI to generate a new Sequelize model. Type this command to create a model for `Classroom`, `Student`, `Lecturer`, `Course`, and `StudentCourse`.
sequelize model:create --name Classroom --attributes class_name:string
sequelize model:create --name Student --attributes classroom_id:integer,student_name:string
sequelize model:create --name Lecturer --attributes lecturer_name:string
sequelize model:create --name Course --attributes lecturer_id:integer,course_name:string
sequelize model:create --name StudentCourse --attributes student_id:integer,course_id:integer
That command creates a model file to the model's folder and a migration file to folder migrations. Next, modify `models/classroom.js` then add association with `Student` model inside `associate` function.
class Classroom extends Model {
static associate(models) {
Classroom.hasMany(models.Student, {
foreignKey: 'classroom_id',
as: 'students',
});
}
};
Next, modify `models/student.js` then add association with `Classroom` and `Coursemodel` models inside `associate` function.
class Student extends Model {
static associate(models) {
Student.belongsTo(models.Classroom, {
foreignKey: 'classroom_id',
as: 'classroom'
});
Student.belongsToMany(models.Course, {
through: 'StudentCourse',
as: 'courses',
foreignKey: 'student_id'
});
}
};
Next, modify `models/lecturer.js` then add the association with the `Course` model inside the `associate` function.
class Lecturer extends Model {
static associate(models) {
Lecturer.hasOne(models.Course, {
foreignKey: 'lecturer_id',
as: 'course',
});
}
};
Next, modify `models/course.js` then add association with `Student` and `Lecturer` models inside `associate` function.
class Course extends Model {
static associate(models) {
Course.belongsToMany(models.Student, {
through: 'StudentCourse',
as: 'students',
foreignKey: 'course_id'
});
Course.belongsTo(models.Lecturer, {
foreignKey: 'lecturer_id',
as: 'lecturer'
});
}
};
Finally, for migrations, there's nothing to change, and they all ready to generate the table to the PostgreSQL Database. Type this command to generate the table to the database using Sequelize.
sequelize db:migrate
To create the controller, first, create a folder for controllers and a new Javascript file by type these commands.
mkdir controllers
touch controllers/classroom.js
Open and edit `controllers/classroom.js` then add these lines of codes.
const Classroom = require('../models').Classroom;
const Student = require('../models').Student;
module.exports = {
list(req, res) {
return Classroom
.findAll({
include: [{
model: Student,
as: 'students'
}],
order: [
['createdAt', 'DESC'],
[{ model: Student, as: 'students' }, 'createdAt', 'DESC'],
],
})
.then((classrooms) => res.status(200).send(classrooms))
.catch((error) => { res.status(400).send(error); });
},
getById(req, res) {
return Classroom
.findByPk(req.params.id, {
include: [{
model: Student,
as: 'students'
}],
})
.then((classroom) => {
if (!classroom) {
return res.status(404).send({
message: 'Classroom Not Found',
});
}
return res.status(200).send(classroom);
})
.catch((error) => {
console.log(error);
res.status(400).send(error);
});
},
add(req, res) {
return Classroom
.create({
class_name: req.body.class_name,
})
.then((classroom) => res.status(201).send(classroom))
.catch((error) => res.status(400).send(error));
},
update(req, res) {
return Classroom
.findByPk(req.params.id, {
include: [{
model: Student,
as: 'students'
}],
})
.then(classroom => {
if (!classroom) {
return res.status(404).send({
message: 'Classroom Not Found',
});
}
return classroom
.update({
class_name: req.body.class_name || classroom.class_name,
})
.then(() => res.status(200).send(classroom))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
delete(req, res) {
return Classroom
.findByPk(req.params.id)
.then(classroom => {
if (!classroom) {
return res.status(400).send({
message: 'Classroom Not Found',
});
}
return classroom
.destroy()
.then(() => res.status(204).send())
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
};
In that controller, we have all CRUD (Create, Read, Update, and Delete) functions. To make this controller available via the controller's folder, add these files for declaring this controller file and other controllers files.
touch controllers/index.js
Open and edit that file then add these lines of Javascript codes.
const classroom = require('./classroom');
module.exports = {
classroom,
};
For the router, we will use the existing router that generated by Express Generator. Open and edit `routes/index.js` then declare the Classroom controller after other variables.
const classroomController = require('../controllers').classroom;
Add these routes after the existing route for the Classroom controller.
router.get('/api/classroom', classroomController.list);
router.get('/api/classroom/:id', classroomController.getById);
router.post('/api/classroom', classroomController.add);
router.put('/api/classroom/:id', classroomController.update);
router.delete('/api/classroom/:id', classroomController.delete);
Type this command to create a controller and router file for a Student model.
touch controllers/student.js
Open and edit `controllers/student.js` then add these lines of codes that contain full CRUD function for the Student model.
const Student = require('../models').Student;
const Classroom = require('../models').Classroom;
const Course = require('../models').Course;
module.exports = {
list(req, res) {
return Student
.findAll({
include: [{
model: Classroom,
as: 'classroom'
},{
model: Course,
as: 'courses'
}],
order: [
['createdAt', 'DESC'],
[{ model: Course, as: 'courses' }, 'createdAt', 'DESC'],
],
})
.then((students) => res.status(200).send(students))
.catch((error) => { res.status(400).send(error); });
},
getById(req, res) {
return Student
.findByPk(req.params.id, {
include: [{
model: Classroom,
as: 'classroom'
},{
model: Course,
as: 'courses'
}],
})
.then((student) => {
if (!student) {
return res.status(404).send({
message: 'Student Not Found',
});
}
return res.status(200).send(student);
})
.catch((error) => res.status(400).send(error));
},
add(req, res) {
return Student
.create({
classroom_id: req.body.classroom_id,
student_name: req.body.student_name,
})
.then((student) => res.status(201).send(student))
.catch((error) => res.status(400).send(error));
},
update(req, res) {
return Student
.findByPk(req.params.id, {
include: [{
model: Classroom,
as: 'classroom'
},{
model: Course,
as: 'courses'
}],
})
.then(student => {
if (!student) {
return res.status(404).send({
message: 'Student Not Found',
});
}
return student
.update({
student_name: req.body.student_name || student.student_name,
})
.then(() => res.status(200).send(student))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
delete(req, res) {
return Student
.findByPk(req.params.id)
.then(student => {
if (!student) {
return res.status(400).send({
message: 'Student Not Found',
});
}
return student
.destroy()
.then(() => res.status(204).send())
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
};
Next, open and edit `controllers/index.js` then register the Student controller in that file.
const classroom = require('./classroom');
const student = require('./student');
module.exports = {
classroom,
student,
};
Next, open and edit `routes/index.js` then add a required variable for the student controller.
const studentController = require('../controllers').student;
Add the routes for all CRUD functions of the student controller.
router.get('/api/student', studentController.list);
router.get('/api/student/:id', studentController.getById);
router.post('/api/student', studentController.add);
router.put('/api/student/:id', studentController.update);
router.delete('/api/student/:id', studentController.delete);
Type this command to create a controller and router file for the Lecturer model.
touch controllers/lecturer.js
Open and edit `controllers/lecturer.js` then add these lines of codes that contain full CRUD function for the Lecturer model.
const Lecturer = require('../models').Lecturer;
const Course = require('../models').Course;
module.exports = {
list(req, res) {
return Lecturer
.findAll({
include: [{
model: Course,
as: 'course'
}],
order: [
['createdAt', 'DESC'],
[{ model: Course, as: 'course' }, 'createdAt', 'DESC'],
],
})
.then((lecturers) => res.status(200).send(lecturers))
.catch((error) => { res.status(400).send(error); });
},
getById(req, res) {
return Lecturer
.findByPk(req.params.id, {
include: [{
model: Course,
as: 'course'
}],
})
.then((lecturer) => {
if (!lecturer) {
return res.status(404).send({
message: 'Lecturer Not Found',
});
}
return res.status(200).send(lecturer);
})
.catch((error) => res.status(400).send(error));
},
add(req, res) {
return Lecturer
.create({
lecturer_name: req.body.lecturer_name,
})
.then((lecturer) => res.status(201).send(lecturer))
.catch((error) => res.status(400).send(error));
},
update(req, res) {
return Lecturer
.findByPk(req.params.id, {
include: [{
model: Course,
as: 'course'
}],
})
.then(lecturer => {
if (!lecturer) {
return res.status(404).send({
message: 'Lecturer Not Found',
});
}
return lecturer
.update({
lecturer_name: req.body.lecturer_name || classroom.lecturer_name,
})
.then(() => res.status(200).send(lecturer))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
delete(req, res) {
return Lecturer
.findByPk(req.params.id)
.then(lecturer => {
if (!lecturer) {
return res.status(400).send({
message: 'Lecturer Not Found',
});
}
return lecturer
.destroy()
.then(() => res.status(204).send())
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
};
Next, open and edit `controllers/index.js` then register the Lecturer controller in that file.
const classroom = require('./classroom');
const student = require('./student');
const lecturer = require('./lecturer');
module.exports = {
classroom,
student,
lecturer,
};
Next, open and edit `routes/index.js` then add a required variable for the lecturer controller.
const lecturerController = require('../controllers').lecturer;
Add the routes for all CRUD functions of the lecturer controller.
router.get('/api/lecturer', lecturerController.list);
router.get('/api/lecturer/:id', lecturerController.getById);
router.post('/api/lecturer', lecturerController.add);
router.put('/api/lecturer/:id', lecturerController.update);
router.delete('/api/lecturer/:id', lecturerController.delete);
Type this command to create a controller and router file for the Course model.
touch controllers/course.js
Open and edit `controllers/course.js` then add these lines of codes that contain full CRUD function for the Course model.
const Course = require('../models').Course;
const Student = require('../models').Student;
const Lecturer = require('../models').Lecturer;
module.exports = {
list(req, res) {
return Course
.findAll({
include: [{
model: Student,
as: 'students'
},{
model: Lecturer,
as: 'lecturer'
}],
order: [
['createdAt', 'DESC'],
[{ model: Student, as: 'students' }, 'createdAt', 'DESC'],
],
})
.then((courses) => res.status(200).send(courses))
.catch((error) => { res.status(400).send(error); });
},
getById(req, res) {
return Course
.findByPk(req.params.id, {
include: [{
model: Course,
as: 'course'
}],
})
.then((course) => {
if (!course) {
return res.status(404).send({
message: 'Course Not Found',
});
}
return res.status(200).send(course);
})
.catch((error) => res.status(400).send(error));
},
add(req, res) {
return Course
.create({
course_name: req.body.course_name,
})
.then((course) => res.status(201).send(course))
.catch((error) => res.status(400).send(error));
},
update(req, res) {
return Course
.findByPk(req.params.id, {
include: [{
model: Course,
as: 'course'
}],
})
.then(course => {
if (!course) {
return res.status(404).send({
message: 'Course Not Found',
});
}
return course
.update({
course_name: req.body.course_name || classroom.course_name,
})
.then(() => res.status(200).send(course))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
delete(req, res) {
return Course
.findByPk(req.params.id)
.then(course => {
if (!course) {
return res.status(400).send({
message: 'Course Not Found',
});
}
return course
.destroy()
.then(() => res.status(204).send())
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
};
Next, open and edit `controllers/index.js` then register the Course controller in that file.
const classroom = require('./classroom');
const student = require('./student');
const lecturer = require('./lecturer');
const course = require('./course');
module.exports = {
classroom,
student,
lecturer,
course,
};
Next, open and edit `routes/index.js` then add a required variable for the course controller.
const courseController = require('../controllers').course;
Add the routes for all CRUD functions of the course controller.
router.get('/api/course', courseController.list);
router.get('/api/course/:id', courseController.getById);
router.post('/api/course', courseController.add);
router.put('/api/course/:id', courseController.update);
router.delete('/api/course/:id', courseController.delete);
Now, we have to make the association more useful. To make a Classroom include the students, add this function to `controllers/classroom.js`.
addWithStudents(req, res) {
return Classroom
.create({
class_name: req.body.class_name,
students: req.body.students,
}, {
include: [{
model: Student,
as: 'students'
}]
})
.then((classroom) => res.status(201).send(classroom))
.catch((error) => res.status(400).send(error));
},
Next, add this new function to the route file `routes/index.js`.
router.post('/api/classroom/add_with_students', classroomController.addWithStudents);
To add a lecturer include a course, add this function to `controllers/lecturer.js`.
addWithCourse(req, res) {
return Lecturer
.create({
lecturer_name: req.body.lecturer_name,
course: req.body.course
}, {
include: [{
model: Course,
as: 'course'
}]
})
.then((lecturer) => res.status(201).send(lecturer))
.catch((error) => res.status(400).send(error));
},
Next, add this new function to the route file `routes/index.js`.
router.post('/api/lecturer/add_with_course', lecturerController.addWithCourse);
To add a course for a student, add this function to `controllers/student.js`.
addCourse(req, res) {
return Student
.findByPk(req.body.student_id, {
include: [{
model: Classroom,
as: 'classroom'
},{
model: Course,
as: 'courses'
}],
})
.then((student) => {
if (!student) {
return res.status(404).send({
message: 'Student Not Found',
});
}
Course.findByPk(req.body.course_id).then((course) => {
if (!course) {
return res.status(404).send({
message: 'Course Not Found',
});
}
student.addCourse(course);
return res.status(200).send(student);
})
})
.catch((error) => res.status(400).send(error));
},
Next, add this new function to the route file `routes/index.js`.
router.post('/api/student/add_course', studentController.addCourse);
That's a few of the Association features that might be useful for your project. We will add another useful function to this article later.
Type this command to run the application.
nodemon
Open the new terminal tab or command line tab then type this command for save or persist classroom data include with students.
curl -i -X POST -H "Content-Type: application/json" -d '{ "class_name":"Class A","students": [{ "student_name":"Mya Lynch" },{ "student_name":"Joseph Norton" },{ "student_name":"Dedric Reinger" }] }' localhost:3000/api/classroom/add_with_students
To see data persist to PostgreSQL table, open a new terminal tab then run `psql`.
psql postgres -U codequs
Connect to the database then running the queries.
postgres=> \c node_sequelize
node_sequelize=> SELECT * FROM public."Classrooms";
id | class_name | createdAt | updatedAt
----+------------+----------------------------+----------------------------
2 | Class A | 2021-07-24 09:18:30.062+07 | 2021-07-24 09:18:30.062+07
(1 row)
node_sequelize=> SELECT * FROM public."Students" WHERE classroom_id=2;
id | classroom_id | student_name | createdAt | updatedAt
----+--------------+--------------+----------------------------+----------------------------
1 | 2 | Mya Lynch | 2021-07-24 09:18:30.125+07 | 2021-07-24 09:18:30.125+07
2 | 2 | Joseph Norton | 2021-07-24 09:18:30.125+07 | 2021-07-24 09:18:30.125+07
3 | 2 | Dedric Reinger| 2021-07-24 09:18:30.125+07 | 2021-07-24 09:18:30.125+07
(3 rows)
Using `curl` you just get a classroom then the students will be included with the response.
curl -i -H "Accept: application/json" localhost:3000/api/classroom/2
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 512
ETag: W/"200-9RPafOJtDdkqqMBVkSNCFoQ3p9s"
Date: Tue, 24 Jul 2021 03:18:45 GMT
Connection: keep-alive
{"id":2,"class_name":"Class A","createdAt":"2021-07-24T02:18:30.062Z","updatedAt":"2021-07-24T02:18:30.062Z","students":[{"id":1,"classroom_id":2,"student_name":"Mya Lynch","createdAt":"2021-07-24T02:18:30.125Z","updatedAt":"2021-07-24T02:18:30.125Z"},{"id":2,"classroom_id":2,"student_name":"Joseph Norton","createdAt":"2018-07-24T02:18:30.125Z","updatedAt":"2021-07-24T02:18:30.125Z"},{"id":3,"classroom_id":2,"student_name":"Norton Reinger","createdAt":"2021-07-24T02:18:30.125Z","updatedAt":"2021-07-24T02:18:30.125Z"}]}
Run this `curl` for save or persist Lecturer, Course, and Student/Course data.
curl -i -X POST -H "Content-Type: application/json" -d '{ "lecturer_name":"Imani Gorczany","course": { "course_name":"English Grammar" }}' localhost:3000/api/lecturer/add_with_course
curl -i -X POST -H "Content-Type: application/json" -d '{ "student_id":1,"course_id": 1}' localhost:3000/api/student/add_course
Now, you can see the data exists using `psql` query for each table.
In this video we build a rest api with NodeJS (JavaScript) and PostreSQL.
In this video we tackle
* routing concepts
* the express framework
* how to use Postman to test your routes
* how to create a database in the psql shell
* performing SQL queries
* callback functions
1655692231
Being able to connect to a database from a web application and read data from it is an essential skill for all software developers to have. It is ubiquitous and the backbone of all modern, real world applications.
In this video We show how to connect to a PostgreSQL database from a JavaScript web app using Node.JS, Express.JS, PostgreSQL, and the pg-promise library
Download the sample database from https://postgresqltutorial.com
Subscribe: https://www.youtube.com/channel/UC2bxlj2Hfb1zqIT24QXzXyQ/featured
1654664700
今こそ、リレーショナルデータベースとSQLを学ぶ絶好の機会です。Web開発からデータサイエンスまで、どこでも使用されています。
Stack Overflow 2021調査では、プロの開発者が使用した上位5つのデータベーステクノロジのうち4つは、リレーショナルデータベース管理システムでした。
PostgreSQLは、最初に学習するリレーショナルデータベース管理システムとして優れた選択肢です。
freeCodeCampリレーショナルデータベース認定から学習している場合でも、自分のコンピューターでPostgreSQLを試している場合でも、データベースを作成および管理し、データベースにデータを挿入し、データベースからデータをクエリする方法が必要です。
PostgreSQLと対話するためのグラフィカルアプリケーションはいくつかありますが、psqlとコマンドラインを使用することが、データベースと通信するための最も直接的な方法である可能性があります。
psqlは、ターミナルインターフェイスを介してPostgreSQLデータベースと対話できるようにするツールです。PostgreSQLをマシンにインストールすると、psqlが自動的に含まれます。
psqlを使用すると、SQLクエリを記述し、それらをPostgreSQLに送信して、結果を表示できます。また、データベースを管理するためのメタコマンド(円記号で始まる)を使用することもできます。スクリプトを記述して、データベースに関連するタスクを自動化することもできます。
さて、ローカルコンピュータでデータベースを実行し、コマンドラインを使用することは、最初は恐ろしいように思えるかもしれません。私はそれが本当にそれほど悪くないことをあなたに言うためにここにいます。このガイドでは、データベースの作成、管理、バックアップ、復元の方法など、コマンドラインからPostgreSQLデータベースを管理するための基本について説明します。
コンピュータにPostgreSQLをまだインストールしていない場合は、PostgreSQLの公式ドキュメントに記載されているオペレーティングシステムの手順に従ってください。
PostgreSQLをインストールすると、パスワードの入力を求められます。作成するデータベースに接続するために必要になるため、これは安全な場所に保管してください。
psqlを使用してデータベースに接続する場合、2つのオプションがあります。コマンドラインまたはpsqlアプリケーションを使用して接続できます。どちらもほぼ同じエクスペリエンスを提供します。
ターミナルを開きます。と入力すると、psqlがインストールされていることを確認できますpsql --version
。が表示されます。これは、マシンにインストールされているPostgreSQLのバージョンですpsql (PostgreSQL) version_number
。version_number
私の場合は14.1です。
コマンドラインからpsqlのバージョンを確認する
データベースに接続するためのパターンは次のとおりです。
psql -d database_name -U username
-d
フラグはの代わりになり--dbname
ます-U
が、の代わりになり--username
ます。
PostgreSQLをインストールすると、デフォルトのデータベースとユーザーが作成され、どちらも。と呼ばれpostgres
ます。したがって、Enterキーを押して、スーパーユーザーとしてデータベースpsql -d postgres -U postgres
に接続します。postgrespostgres
psql -d postgres -U postgres
パスワードの入力を求められます。コンピューターにPostgreSQLをインストールしたときに選択したパスワードを入力します。ターミナルプロンプトが変わり、postgres
データベースに接続していることを示します。
psqlを使用してコマンドラインからデータベースに接続する
(スーパーユーザーとしてではなくpostgres
)自分自身としてデータベースに直接接続する場合は、ユーザー名の値としてシステムのユーザー名を入力します。
psqlアプリケーションを起動します–「SQLシェル(psql)」と呼ばれます。サーバー、データベース、ポート、およびユーザー名の入力を求められます。localhost
Enterキーを押すだけでpostgres
、デフォルト値(、、、、、および)を選択でき5432
ますpostgres
。
次に、PostgreSQLのインストール時に選択したパスワードの入力を求められます。これを入力すると、ターミナルプロンプトが変わり、postgres
データベースに接続していることが示されます。
psqlアプリケーションを使用してデータベースに接続する
注: Windowsを使用している場合は、「コンソールコードページ(850)はWindowsコードページ(1252)とは異なります。8ビット文字が正しく機能しない可能性があります。詳細については、psqlリファレンスページの「Windowsユーザー向けの注意事項」を参照してください。」この段階では、これについて心配する必要はありません。詳細については、psqlのドキュメントを参照してください。
すべてのpsqlメタコマンドのリストと、それらの機能の概要を表示するには、\?
コマンドを使用します。
\?
psqlのヘルプコマンド
PostgreSQLコマンドのヘルプが必要な場合は、またはとコマンドを使用し\h
て\help
ください。
\h COMMAND
これにより、コマンドの説明、その構文(角括弧内のオプション部分を含む)、およびPostgreSQLドキュメントの関連部分のURLが提供されます。
DROPTABLEステートメントを説明するpsql
時間がかかるコマンドを実行したり、コンソールに大量の情報を出力したりした場合は、。と入力してコマンドを終了できますq
。
q
データベースを管理する前に、データベースを作成する必要があります。
注: SQLコマンドはセミコロンで終了する必要がありますが、メタコマンド(円記号で始まる)はセミコロンで終了する必要はありません。
データベースを作成するためのSQLコマンドは次のとおりです。
CREATE DATABASE database_name;
このガイドでは、本のデータを処理するので、というデータベースを作成しましょうbooks_db
。
CREATE DATABASE books_db;
listコマンドを使用して、使用可能なすべてのデータベースのリストを表示できます。
\l
すべてのデータベースの一覧表示
、、、、およびが表示books_db
されます。(このコマンドは、実際にはと呼ばれる標準データベースをコピーすることで機能します。これについて詳しくは、PostgreSQLのドキュメントを参照してください。)postgrestemplate0template1CREATE DATABASEtemplate1
を使用\l+
すると、データベースのサイズやそのテーブルスペース(データベースを表すファイルが保存されるファイルシステム内の場所)などの追加情報が表示されます。
\l+
追加情報を含むすべてのデータベースの一覧表示
現在、デフォルトのpostgres
データベースに接続しています。データベースに接続したり、データベースを切り替えたりするには、\c
コマンドを使用します。
\c database_name
だから\c books_db
あなたをbooks_db
データベースに接続します。現在接続しているデータベースを反映して、ターミナルプロンプトが変化することに注意してください。
データベースの切り替え
データベースを削除する場合は、DROP DATABASE
コマンドを使用します。
DROP DATABASE database_name;
postgres
などのスーパーユーザーである場合、またはデータベースの所有者である場合にのみ、データベースを削除できます。
存在しないデータベースを削除しようとすると、エラーが発生します。IF EXISTS
代わりに通知を受け取るために使用します。
DROP DATABASE IF EXISTS database_name;
データベースの削除
アクティブな接続があるデータベースを削除することはできません。したがって、現在接続しているデータベースを削除する場合は、別のデータベースに切り替える必要があります。
テーブルを管理する前に、いくつかのテーブルを作成し、それらにサンプルデータを入力する必要があります。
テーブルを作成するコマンドは次のとおりです。
CREATE TABLE table_name();
これにより、空のテーブルが作成されます。列の値を括弧に渡して、列のあるテーブルを作成することもできます。少なくとも、基本テーブルには、主キー(各行を区別するための一意の識別子)と、データを含む列が必要です。
私たちbooks_db
のために、著者用のテーブルと本用のテーブルを作成します。著者の場合、名前と名前を記録します。書籍については、タイトルと出版年を記録します。
著者first_name
とlast_name
本title
がnullでないことを確認します。これは、著者について知るための非常に重要な情報だからです。これを行うために、NOT NULL
制約を含めます。
CREATE TABLE authors(
author_id SERIAL PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL
);
CREATE TABLE books(
book_id SERIAL PRIMARY KEY,
title VARCHAR(100) NOT NULL,
published_year INT
);
CREATE TABLE
テーブルが正常に作成された場合は、端末に印刷されたことが表示されます。
次に、本に外部キーを追加して、2つのテーブルを接続しましょう。外部キーは、別のテーブルの主キーを参照する一意の識別子です。もちろん、本には複数の著者がいる可能性がありますが、今のところ、多対多の関係の複雑さに立ち入るつもりはありません。
books
次のコマンドを使用して、に外部キーを追加します。
ALTER TABLE books ADD COLUMN author_id INT REFERENCES authors(author_id);
次に、いくつかのサンプルデータをテーブルに挿入しましょう。から始めましょうauthors
。
INSERT INTO authors (first_name, last_name)
VALUES (‘Tamsyn’, ‘Muir’), (‘Ann’, ‘Leckie’), (‘Zen’, ‘Cho’);
からすべてを選択しauthors
て、挿入コマンドが機能したことを確認します。
SELECT * FROM authors;
著者テーブルからのすべてのデータのクエリ
次に、いくつかの本のデータをに挿入しbooks
ます。
INSERT INTO books(title, published_year, author_id)
VALUES (‘Gideon the Ninth’, 2019, 1), (‘Ancillary Justice’, 2013, 2), (‘Black Water Sister’, 2021, 3);
実行するSELECT * FROM books;
と、本のデータが表示されます。
Booksテーブルからのすべてのデータのクエリ
このコマンドを使用し\dt
て、データベース内のすべてのテーブルを一覧表示できます。
\dt
あなたがbooks_db
見るbooks
と。authors
とも表示books_book_id_seq
されauthors_author_id_seq
ます。SERIAL
これらは、主キーを生成するために使用したため、テーブルによってIDとして使用される整数のシーケンスを追跡します。
データベース内のすべてのテーブルの一覧表示
特定のテーブルに関する詳細を表示するには、describetableコマンドを使用できます\d table_name
。これにより、列、インデックス、および他のテーブルへの参照が一覧表示されます。
\d table_name
著者テーブルの説明
を使用\dt+ table_name
すると、ストレージや圧縮などの詳細情報が提供されます。
テーブルの名前を変更する必要がある場合は、ALTER TABLE
コマンドを使用して名前を変更できます。
ALTER TABLE table_name RENAME TO new_table_name;
テーブルを削除する場合は、コマンドを使用できますDROP TABLE
。
DROP TABLE table_name;
存在しないテーブルを削除しようとすると、エラーが発生します。IF EXISTS
ステートメントにオプションを含めることで、これを回避できます。このようにして、代わりに通知を受け取ります。
DROP TABLE IF EXISTS table_name;
より長いSQLクエリを作成している場合、コマンドラインはそれを行うための最も人間工学的な方法ではありません。SQLをファイルに書き込んでから、psqlに実行させる方がおそらく良いでしょう。
psqlを使用していて、次のクエリが長くなると思われる場合は、psqlからテキストエディタを開いてそこに書き込むことができます。既存のクエリがある場合、またはサンプルデータをロードするために複数のクエリを実行したい場合は、すでに書き込まれているファイルからコマンドを実行できます。
コマンドを入力する\e
と、psqlはテキストエディタを開きます。エディターを保存して閉じると、psqlは作成したコマンドを実行します。
\e
テキストエディタでコマンドを書く
Windowsでは、psqlのデフォルトのテキストエディタはメモ帳ですが、MacOとLinuxではviです。EDITOR
コンピューターの環境変数に値を設定することで、これを別のエディターに変更できます。
実行するコマンドが特に長い場合や複数のコマンドがある場合は、事前にファイルにSQLを記述し、準備ができたらpsqlにそのファイルを実行させることをお勧めします。
この\i
コマンドを使用すると、ファイルを端末に入力したかのように、ファイルから入力を読み取ることができます。
\i path_to_file/file_name.sql
注:このコマンドをWindowsで実行している場合でも、ファイルパスでスラッシュを使用する必要があります。
パスを指定しない場合、psqlはPostgreSQLに接続する前に最後にいたディレクトリでファイルを検索します。
ファイルからのSQLコマンドの実行
クエリにかかる時間を確認したい場合は、クエリの実行タイミングをオンにすることができます。
\timing
これにより、クエリの完了にかかった時間がミリ秒単位で表示されます。
コマンドを再度実行する\timing
と、クエリの実行タイミングがオフになります。
クエリ実行タイミングの使用
データを含むCSVファイルがあり、これをPostgreSQLデータベースにロードする場合は、コマンドラインからpsqlを使用してこれを行うことができます。
まず、次の構造で呼び出されるCSVファイルを作成しますfilms.csv
(Excel、Googleスプレッドシート、Numbers、またはその他のプログラムを使用するかどうかは関係ありません)。
ピクサーフィルムデータを含むスプレッドシート
psqlを開き、films_db
データベースを作成して接続し、films
テーブルを作成します。
CREATE DATABASE films_db;
\c films_db
CREATE TABLE films(
id SERIAL PRIMARY KEY,
title VARCHAR(100),
year INT,
running_time INT
);
次に、コマンドを使用し\copy
てCSVファイルをにインポートできますfilms
。CSVファイルがコンピューター上にある場所への絶対パスを指定する必要があります。
\copy films(title, year, running_time) FROM 'path_to_file' DELIMITER ‘,’ CSV HEADER;
このDELIMITER
オプションは、インポートされるファイルの各行の列を区切る文字をCSV
指定し、それがCSVファイルであることをHEADER
指定し、ファイルに列の名前を含むヘッダー行が含まれることを指定します。
注:テーブルの列名はのfilms
列名と一致する必要はありませんがfilms.csv
、同じ順序である必要があります。
SELECT * FROM films;
プロセスが成功したかどうかを確認するために使用します。
.csvファイルからのデータのインポート
pg_dump
データベースをバックアップする必要がある場合pg_dump
は、データベースをSQLスクリプトファイルまたは他の種類のアーカイブファイルに抽出できるユーティリティです。
まず、コマンドライン(psqlではない)で、PostgreSQLbin
フォルダーに移動します。
cd "C:\Program Files\PostgreSQL\14\bin"
次に、ユーザー名としてを使用して次のコマンドを実行し、使用postgres
するデータベースと出力ファイルを入力します。
pg_dump -U username database_name > path_to_file/filename.sql
ユーザー名にを使用すると、スーパーユーザーのパスワードの入力postgres
を求められます。次に、データベースの再作成に必要なSQLコマンドを含むファイルを作成します。postgrespg_dump.sql
データベースを.sqlファイルにバックアップする
出力ファイルのパスを指定しない場合は、pg_dump
PostgreSQLに接続する前に最後にあったディレクトリにファイルを保存します。
Films.sqlバックアップファイルの内容
-v
または--verbose
フラグを渡して、各ステップでpg_dump
何が行われているかを確認できます。pg_dump
pg_dumpを冗長モードで実行する
.tar
データベースを(アーカイブ形式)などの他のファイル形式にバックアップすることもできます。
pg_dump -U username -F t database_name > path_to_file/filename.tar
ここで、-F
フラグはpg_dump
、出力形式を指定するt
ことを示し、その.tar
形式になることを示します。
psqlまたはpg_restore
ユーティリティを使用して、バックアップファイルからデータベースを復元できます。どちらを選択するかは、データベースの復元元のファイルの種類によって異なります。
.sql
、psqlを使用します。.tar
、を使用しますpg_restore
。ファイルからデータベースを復元する.sql
には、コマンドラインで(psqlではなく)を使用しますpsql -U username -d database_name -f filename.sql
。
以前に使用したfilms_db
データベースとfilms.sql
ファイルを使用することも、新しいバックアップファイルを作成することもできます。
データを復元するファイル用の空のデータベースを作成します。films.sql
復元に使用している場合films_db
、最も簡単な方法は、削除films_db
して再作成することです。
DROP DATABASE films_db;
CREATE DATABASE films_db;
別のターミナル(psqlではない)で、次のコマンドを実行しpostgres
、ユーザー名、および使用しているデータベースとバックアップファイルの名前を渡します。
psql -U username -d database_name -f path_to_file/filename.sql
フラグはpsql-d
に特定のデータベースを指し、-f
フラグはpsqlに指定されたファイルから読み取るように指示します。
バックアップファイルのパスを指定しない場合、psqlはPostgreSQLに接続する前に最後にあったディレクトリでファイルを検索します。
スーパーユーザーのパスワードの入力を求めpostgres
られ、psqlがデータベースを再作成している間、一連のコマンドがコマンドラインに出力されます。
psqlを使用したデータベースの復元
このコマンドは、復元中に発生したエラーをすべて無視します。エラーが発生した場合にデータベースの復元を停止する場合は、を渡し--set ON_ERROR_STOP=on
ます。
psql -U username -d database_name --set ON_ERROR_STOP=on -f filename.sql
pg_restore
を使用してデータベースを復元するにはpg_restore
、を使用しますpg_restore -U username -d database_name path_to_file/filename.tar
。
データを復元するファイル用の空のデータベースを作成します。films_db
ファイルから復元する場合films.tar
、最も簡単な方法は、ファイルを削除films_db
して再作成することです。
DROP DATABASE films_db;
CREATE DATABASE films_db;
コマンドライン(psqlではない)で、次のコマンドを実行しpostgres
、ユーザー名、および使用しているデータベースとバックアップファイルの名前を渡します。
pg_restore -U username -d database_name path_to_file/filename.tar
pg_restoreを使用したデータベースの復元
-v
または--verbose
フラグを渡しpg_restore
て、各ステップで何が行われているかを確認することもできます。
詳細モードでのpg_restoreの使用
psqlを終了し、それを終了する場合は、quit
またはを入力し\q
ます。
\q
これにより、psqlアプリケーションを使用している場合は閉じ、コマンドラインからpsqlを使用している場合は通常のコマンドプロンプトに戻ります。
スキーマ、ロール、テーブルスペースの管理など、psqlで実行できることは他にもたくさんあります。ただし、このガイドは、コマンドラインからPostgreSQLデータベースの管理を開始するのに十分なはずです。
PostgreSQLとリレーショナルデータベースについて引き続き学習する際に、このガイドがお役に立てば幸いです。
このストーリーは、もともとhttps://www.freecodecamp.org/news/manage-postgresql-with-psql/で公開されました
1654664400
Ahora es un buen momento para aprender bases de datos relacionales y SQL. Desde el desarrollo web hasta la ciencia de datos, se utilizan en todas partes.
En la encuesta Stack Overflow 2021 , 4 de las 5 principales tecnologías de bases de datos utilizadas por los desarrolladores profesionales eran sistemas de gestión de bases de datos relacionales.
PostgreSQL es una excelente opción como primer sistema de administración de bases de datos relacionales para aprender.
Ya sea que esté aprendiendo de la certificación de base de datos relacional freeCodeCamp o esté probando PostgreSQL en su propia computadora, necesita una forma de crear y administrar bases de datos, insertar datos en ellas y consultar datos de ellas.
Si bien existen varias aplicaciones gráficas para interactuar con PostgreSQL, usar psql y la línea de comandos es probablemente la forma más directa de comunicarse con su base de datos.
psql es una herramienta que le permite interactuar con bases de datos PostgreSQL a través de una interfaz de terminal. Cuando instala PostgreSQL en una máquina, psql se incluye automáticamente.
psql le permite escribir consultas SQL, enviarlas a PostgreSQL y ver los resultados. También le permite usar metacomandos (que comienzan con una barra invertida) para administrar las bases de datos. Incluso puede escribir scripts y automatizar tareas relacionadas con sus bases de datos.
Ahora, ejecutar una base de datos en su computadora local y usar la línea de comando puede parecer intimidante al principio. Estoy aquí para decirles que realmente no es tan malo. Esta guía le enseñará los aspectos básicos de la administración de bases de datos de PostgreSQL desde la línea de comandos, incluido cómo crear, administrar, respaldar y restaurar bases de datos.
Si aún no ha instalado PostgreSQL en su computadora, siga las instrucciones para su sistema operativo en la documentación oficial de PostgreSQL .
Cuando instale PostgreSQL, se le pedirá una contraseña. Guárdelo en un lugar seguro, ya que lo necesitará para conectarse a cualquier base de datos que cree.
Tiene dos opciones cuando usa psql para conectarse a una base de datos: puede conectarse a través de la línea de comando o usando la aplicación psql. Ambos proporcionan prácticamente la misma experiencia.
Abre una terminal. Puede asegurarse de que psql esté instalado escribiendo psql --version
. Debería ver psql (PostgreSQL) version_number
dónde version_number
está la versión de PostgreSQL que está instalada en su máquina. En mi caso, es 14.1.
Comprobando la versión de psql a través de la línea de comando
El patrón para conectarse a una base de datos es:
psql -d database_name -U username
La -d
bandera es una alternativa más corta para --dbname
while -U
es una alternativa para --username
.
Cuando instaló PostgreSQL, se crearon una base de datos y un usuario predeterminados, ambos llamados postgres
. Así que ingrese psql -d postgres -U postgres
para conectarse a la postgres
base de datos como postgres
superusuario.
psql -d postgres -U postgres
Se te solicitará una contraseña. Ingrese la contraseña que eligió cuando instaló PostgreSQL en su computadora. El indicador de su terminal cambiará para mostrar que ahora está conectado a la base de postgres
datos.
Conexión a una base de datos desde la línea de comandos con psql
Si desea conectarse directamente a una base de datos como usted mismo (en lugar de como postgres
superusuario), ingrese el nombre de usuario de su sistema como el valor de nombre de usuario.
Inicie la aplicación psql: se llamará "SQL Shell (psql)". Se le pedirá un servidor, una base de datos, un puerto y un nombre de usuario. Simplemente presione enter para seleccionar los valores predeterminados, que son localhost
, postgres
, 5432
y postgres
.
A continuación, se le pedirá la contraseña que eligió cuando instaló PostgreSQL. Una vez que ingrese esto, el indicador de su terminal cambiará para mostrar que está conectado a la base de postgres
datos.
Conexión a una base de datos con la aplicación psql
Nota: si está en Windows, es posible que vea una advertencia como “La página de códigos de la consola (850) difiere de la página de códigos de Windows (1252) Es posible que los caracteres de 8 bits no funcionen correctamente. Consulte la página de referencia de psql 'Notas para usuarios de Windows' para obtener más detalles". No necesita preocuparse por esto en esta etapa. Si desea obtener más información al respecto, consulte la documentación de psql .
Para ver una lista de todos los metacomandos de psql y un breve resumen de lo que hacen, use el \?
comando.
\?
comando de ayuda de psql
Si desea ayuda con un comando de PostgreSQL, use \h
o \help
y el comando.
\h COMMAND
Esto le dará una descripción del comando, su sintaxis (con partes opcionales entre corchetes) y una URL para la parte relevante de la documentación de PostgreSQL.
psql que describe la instrucción DROP TABLE
Si ejecutó un comando que tarda mucho tiempo o imprime demasiada información en la consola, puede salir escribiendo q
.
q
Antes de que pueda administrar cualquier base de datos, deberá crear una.
Nota: los comandos SQL deben terminar con un punto y coma, mientras que los metacomandos (que comienzan con una barra invertida) no necesitan hacerlo.
El comando SQL para crear una base de datos es:
CREATE DATABASE database_name;
Para esta guía, vamos a trabajar con datos de libros, así que vamos a crear una base de datos llamada books_db
.
CREATE DATABASE books_db;
Puede ver una lista de todas las bases de datos disponibles con el comando list.
\l
Listado de todas las bases de datos
Debería ver books_db
, así como postgres
, template0
y template1
. (El CREATE DATABASE
comando en realidad funciona copiando la base de datos estándar, llamada template1
. Puede leer más sobre esto en la documentación de PostgreSQL ).
El uso \l+
mostrará información adicional, como el tamaño de las bases de datos y sus espacios de tabla (la ubicación en el sistema de archivos donde se almacenarán los archivos que representan la base de datos).
\l+
Listado de todas las bases de datos con información adicional
Actualmente sigues conectado a la base de datos predeterminada postgres
. Para conectarse a una base de datos o cambiar entre bases de datos, use el \c
comando.
\c database_name
Entonces \c books_db
lo conectará a la base de books_db
datos. Tenga en cuenta que el aviso de su terminal cambia para reflejar la base de datos a la que está conectado actualmente.
Cambio de bases de datos
Si desea eliminar una base de datos, use el DROP DATABASE
comando.
DROP DATABASE database_name;
Solo podrá eliminar una base de datos si es un superusuario, como postgres
, o si es el propietario de la base de datos.
Si intenta eliminar una base de datos que no existe, obtendrá un error. Úselo IF EXISTS
para obtener un aviso en su lugar.
DROP DATABASE IF EXISTS database_name;
Eliminación de una base de datos
No puede eliminar una base de datos que tenga conexiones activas. Entonces, si desea eliminar la base de datos a la que está conectado actualmente, deberá cambiar a otra base de datos.
Antes de que podamos administrar tablas, debemos crear algunas y completarlas con algunos datos de muestra.
El comando para crear una tabla es:
CREATE TABLE table_name();
Esto creará una tabla vacía. También puede pasar valores de columna entre paréntesis para crear una tabla con columnas. Como mínimo, una tabla básica debe tener una clave principal (un identificador único para diferenciar cada fila) y una columna con algunos datos.
Para nuestro books_db
, crearemos una tabla para autores y otra para libros. Para los autores, registraremos su nombre y apellido. Para los libros, registraremos el título y el año en que se publicaron.
Nos aseguraremos de que los autores first_name
y last_name
los libros title
no sean nulos, ya que esta es información bastante vital para saber sobre ellos. Para ello incluimos la NOT NULL
restricción.
CREATE TABLE authors(
author_id SERIAL PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL
);
CREATE TABLE books(
book_id SERIAL PRIMARY KEY,
title VARCHAR(100) NOT NULL,
published_year INT
);
Verá CREATE TABLE
impreso en la terminal si la tabla se creó correctamente.
Ahora conectemos las dos tablas agregando una clave externa a los libros. Las claves externas son identificadores únicos que hacen referencia a la clave principal de otra tabla. Los libros pueden, por supuesto, tener varios autores, pero no vamos a entrar en las complejidades de las relaciones de muchos a muchos en este momento.
Agregue una clave externa books
con el siguiente comando:
ALTER TABLE books ADD COLUMN author_id INT REFERENCES authors(author_id);
A continuación, insertemos algunos datos de muestra en las tablas. Empezaremos con authors
.
INSERT INTO authors (first_name, last_name)
VALUES (‘Tamsyn’, ‘Muir’), (‘Ann’, ‘Leckie’), (‘Zen’, ‘Cho’);
Seleccione todo desde authors
para asegurarse de que el comando de inserción funcionó.
SELECT * FROM authors;
Consultar todos los datos de la tabla de autores
A continuación, insertaremos algunos datos de libros en books
.
INSERT INTO books(title, published_year, author_id)
VALUES (‘Gideon the Ninth’, 2019, 1), (‘Ancillary Justice’, 2013, 2), (‘Black Water Sister’, 2021, 3);
Si corres SELECT * FROM books;
verás los datos del libro.
Consultar todos los datos de la tabla de libros
Puede usar el \dt
comando para listar todas las tablas en una base de datos.
\dt
Porque books_db
verás books
y authors
. También verá books_book_id_seq
y authors_author_id_seq
. Estos realizan un seguimiento de la secuencia de números enteros utilizados como identificadores por las tablas porque solíamos SERIAL
generar sus claves principales.
Listado de todas las tablas en una base de datos
Para ver más información sobre una tabla en particular, puede usar el comando describir tabla: \d table_name
. Esto enumerará las columnas, los índices y cualquier referencia a otras tablas.
\d table_name
Describiendo la tabla de autores
El uso \dt+ table_name
proporcionará más información, como sobre el almacenamiento y la compresión.
Si alguna vez necesita cambiar el nombre de una tabla, puede cambiarle el nombre con el ALTER TABLE
comando.
ALTER TABLE table_name RENAME TO new_table_name;
Si desea eliminar una tabla, puede usar el DROP TABLE
comando.
DROP TABLE table_name;
Si intenta eliminar una tabla que no existe, obtendrá un error. Puede evitar esto al incluir la IF EXISTS
opción en la instrucción. De esta manera, recibirá un aviso en su lugar.
DROP TABLE IF EXISTS table_name;
Si está escribiendo consultas SQL más largas, la línea de comandos no es la forma más ergonómica de hacerlo. Probablemente sea mejor escribir su SQL en un archivo y luego hacer que psql lo ejecute.
Si está trabajando con psql y cree que su próxima consulta será larga, puede abrir un editor de texto desde psql y escribirlo allí. Si tiene una consulta existente, o tal vez desee ejecutar varias consultas para cargar datos de muestra, puede ejecutar comandos desde un archivo que ya está escrito.
Si ingresa el \e
comando, psql abrirá un editor de texto. Cuando guarde y cierre el editor, psql ejecutará el comando que acaba de escribir.
\e
Escribir comandos en un editor de texto
En Windows, el editor de texto predeterminado para psql es Notepad, mientras que en MacOs y Linux es vi. Puede cambiar esto a otro editor configurando el EDITOR
valor en las variables de entorno de su computadora.
Si tiene comandos particularmente largos o múltiples comandos que desea ejecutar, sería mejor escribir el SQL en un archivo con anticipación y hacer que psql ejecute ese archivo una vez que esté listo.
El \i
comando le permite leer la entrada de un archivo como si lo hubiera escrito en la terminal.
\i path_to_file/file_name.sql
Nota: si está ejecutando este comando en Windows, aún necesita usar barras diagonales en la ruta del archivo.
Si no especifica una ruta, psql buscará el archivo en el último directorio en el que estuvo antes de conectarse a PostgreSQL.
Ejecutar comandos SQL desde un archivo
Si desea ver cuánto tardan sus consultas, puede activar el tiempo de ejecución de consultas.
\timing
Esto mostrará en milisegundos el tiempo que tardó en completarse la consulta.
Si \timing
vuelve a ejecutar el comando, desactivará el tiempo de ejecución de la consulta.
Uso del tiempo de ejecución de consultas
Si tiene un archivo CSV con datos y desea cargarlo en una base de datos PostgreSQL, puede hacerlo desde la línea de comandos con psql.
Primero, cree un archivo CSV llamado films.csv
con la siguiente estructura (no importa si usa Excel, Google Sheets, Numbers o cualquier otro programa).
Una hoja de cálculo con datos de películas de Pixar
Abra psql y cree una films_db
base de datos, conéctese a ella y cree una films
tabla.
CREATE DATABASE films_db;
\c films_db
CREATE TABLE films(
id SERIAL PRIMARY KEY,
title VARCHAR(100),
year INT,
running_time INT
);
Luego puede usar el \copy
comando para importar el archivo CSV a films
. Debe proporcionar una ruta absoluta a donde se encuentra el archivo CSV en su computadora.
\copy films(title, year, running_time) FROM 'path_to_file' DELIMITER ‘,’ CSV HEADER;
La DELIMITER
opción especifica el carácter que separa las columnas en cada fila del archivo que se está importando, CSV
especifica que es un archivo CSV y HEADER
especifica que el archivo contiene una línea de encabezado con los nombres de las columnas.
Nota: No es necesario que los nombres de las columnas de la films
tabla coincidan con los nombres de las columnas, films.csv
pero sí deben estar en el mismo orden.
Úselo SELECT * FROM films;
para ver si el proceso fue exitoso.
Importación de datos desde un archivo .csv
pg_dump
Si necesita hacer una copia de seguridad de una base de datos, pg_dump
hay una utilidad que le permite extraer una base de datos en un archivo de script SQL u otro tipo de archivo comprimido.
Primero, en la línea de comando (no en psql), navegue a la bin
carpeta PostgreSQL.
cd "C:\Program Files\PostgreSQL\14\bin"
Luego ejecute el siguiente comando, usando postgres
como nombre de usuario y completando la base de datos y el archivo de salida que desea usar.
pg_dump -U username database_name > path_to_file/filename.sql
Úselo postgres
para el nombre de usuario y se le pedirá la postgres
contraseña de superusuario. pg_dump
luego creará un .sql
archivo que contiene los comandos SQL necesarios para recrear la base de datos.
Copia de seguridad de una base de datos en un archivo .sql
Si no especifica una ruta para el archivo de salida, pg_dump
guardará el archivo en el último directorio en el que estuvo antes de conectarse a PostgreSQL.
Contenido del archivo de copia de seguridad films.sql
Puede pasar la bandera -v
o a para ver qué está haciendo en cada paso.--verbosepg_dumppg_dump
Ejecutando pg_dump en modo detallado
También puede hacer una copia de seguridad de una base de datos en otros formatos de archivo, como .tar
(un formato de archivo).
pg_dump -U username -F t database_name > path_to_file/filename.tar
Aquí la -F
bandera le dice pg_dump
que va a especificar un formato de salida, mientras t
que le dice que va a estar en el .tar
formato.
Puede restaurar una base de datos desde un archivo de respaldo utilizando psql o la pg_restore
utilidad. El que elija depende del tipo de archivo desde el que está restaurando la base de datos.
.sql
, use psql..tar
, use pg_restore
.Para restaurar una base de datos desde un .sql
archivo, en la línea de comando (no en psql), use psql -U username -d database_name -f filename.sql
.
Puede utilizar la base de films_db
datos y films.sql
el archivo que utilizó anteriormente o crear un nuevo archivo de copia de seguridad.
Cree una base de datos vacía para que el archivo restaure los datos. Si está utilizando films.sql
para restaurar films_db
, lo más fácil podría ser eliminarlo films_db
y volver a crearlo.
DROP DATABASE films_db;
CREATE DATABASE films_db;
En una terminal separada (no en psql), ejecute el siguiente comando, pasándolo postgres
como el nombre de usuario y los nombres de la base de datos y el archivo de copia de seguridad que está utilizando.
psql -U username -d database_name -f path_to_file/filename.sql
La -d
bandera apunta a psql a una base de datos específica, mientras que la -f
bandera le dice a psql que lea desde el archivo especificado.
Si no especifica una ruta para el archivo de respaldo, psql buscará el archivo en el último directorio en el que estuvo antes de conectarse a PostgreSQL.
Se le pedirá la postgres
contraseña de superusuario y luego verá una serie de comandos impresos en la línea de comandos mientras psql recrea la base de datos.
Restaurar una base de datos usando psql
Este comando ignora cualquier error que ocurra durante la restauración. Si desea dejar de restaurar la base de datos si se produce un error, pase --set ON_ERROR_STOP=on
.
psql -U username -d database_name --set ON_ERROR_STOP=on -f filename.sql
pg_restore
Para restaurar una base de datos usando pg_restore
, use pg_restore -U username -d database_name path_to_file/filename.tar
.
Cree una base de datos vacía para que el archivo restaure los datos. Si está restaurando films_db
desde un films.tar
archivo, lo más fácil podría ser eliminarlo films_db
y volver a crearlo.
DROP DATABASE films_db;
CREATE DATABASE films_db;
En la línea de comando (no en psql), ejecute el siguiente comando, pasándolo postgres
como nombre de usuario y los nombres de la base de datos y el archivo de copia de seguridad que está utilizando.
pg_restore -U username -d database_name path_to_file/filename.tar
Restaurar una base de datos usando pg_restore
También puede pasar la bandera -v
o --verbose
para ver qué pg_restore
está haciendo en cada paso.
Usando pg_restore en modo detallado
Si ha terminado con psql y quiere salir de él, ingrese quit
o \q
.
\q
Esto cerrará la aplicación psql si la estaba usando, o lo regresará a su símbolo del sistema habitual si estaba usando psql desde la línea de comandos.
Hay muchas más cosas que puede hacer con psql, como administrar esquemas, roles y espacios de tablas. Pero esta guía debería ser suficiente para comenzar a administrar bases de datos PostgreSQL desde la línea de comandos.
Espero que esta guía le resulte útil a medida que continúa aprendiendo sobre PostgreSQL y las bases de datos relacionales.
Esta historia se publicó originalmente en https://www.freecodecamp.org/news/manage-postgresql-with-psql/
1654498680
Waves blockchain — PostgreSQL sync scripts
A set of scripts to download and update Waves blockchain history data into a PostgreSQL 11.x database.
npm install
2. Create config.yml
file in the project, using config.example.yml
for reference.
3. In PostgreSQL, create empty database.
4. Set environment variable MIGRATE
to true
(or just run crawler like this: MIGRATE=true npm run ...
), it will apply initial and all additional migrations to yours database.
5. ⬇️ To download a range of blocks to database:
npm run download {start} {end},
# for example
npm run download 1 100000
Blocks from the range get inserted in a single transaction, so either all get inserted, or none. In our experience ranges of 10000—100000 work best.
6. 🔄 To keep your database up-to-date:
npm run updateComposite
This is a continuous script, so you may want to run it in the background. We recommend using some kind of process manager (e.g. pm2
) to restart the process on crash.
./node_modules/.bin/knex --migrations-directory migrations migrate:make $MIGRATION_NAME
2. Migrate latest:
./node_modules/.bin/knex migrate:latest --client postgresql --connection postgresql://$PGUSER:$PGPASSWORD@$PGHOST:$PGPORT/$PGDATABASE --migrations-directory migrations
# OR
npm run migrate -- --connection postgresql://$PGUSER:$PGPASSWORD@$PGHOST:$PGPORT/$PGDATABASE
Download Details:
Author: wavesplatform
Source Code: https://github.com/wavesplatform/blockchain-postgres-sync
License:
1654485135
In this video we build a rest api with NodeJS (JavaScript) and PostreSQL.
In this video we tackle
* routing concepts
* the express framework
* how to use Postman to test your routes
* how to create a database in the psql shell
* performing SQL queries
* callback functions
Subscribe: https://www.youtube.com/c/AustinBeaufort/featured
1654321740
Two way, incremental sync between React Native realmjs databases and MySQL, Oracle, MS SQL Server and PostgreSQL databases.
For end-to-end testing, you need to first setup a Pervasync server and publish your central database tables for sync. See Pervasync documentation for instructions.
This library is available on npm, install it with: npm install --save react-native-sync
or yarn add react-native-sync
.
import RNSync from "react-native-sync";
2. Configure RNSync:
var settings = {
syncServerUrl: "http://localhost:8080/pervasync/server", // required
syncUserName: "user_1", // required
syncUserPassword: "welcome1", // required
};
await RNSync.config(settings);
3. Start a sync session:
let syncSummary = await RNSync.sync();
4. Get a handle to the synced realm database and synced folder path:
let realm = await RNSync.getRealm(syncSchemaName);
let path = await RNSync.getPath(syncFolderName);
Check out react-native-sync-demo and expecially sync.js
Download Details:
Author: pervasync
Source Code: https://github.com/pervasync/react-native-sync
License: MIT license
#react #reactnative #mobileapp #javascript #backend #postgresql #mysql
1653967514
Este es un ejemplo práctico en el que crearemos una web completa usando Python y JavaScript. Crearemos un Backend usando el Framework de Python Flask y el frontend lo crearemos usando Javascript puro (Vanilla Javascript) desde cero. Básicamente crearemos una REST API, más un frontend, lo estilizaremos con bootstrap5, y aprenderemos a desplegarlo en servicios gratuitos como son Heroku y Heroku Postgres.
Índice del contenido:
00:00 Introducción
01:36 Project/Backend Setup
15:35 REST API Endpoints
20:10 Crear Usuario - Backend
33:51 Obtener Usuarios - Backend
36:25 Obtener Usuario - Backend
40:59 Eliminar Usuario - Backend
44:32 Actualizar Usuario - Backend
50:48 Frontend Setup - Static Files
01:05:22 Crear Usuario - Frontend
01:17:39 Obtener Usuarios - Frontend
01:32:39 Eliminar Usuario - Frontend
01:41:58 Actualizar Usuario - Frontend
01:55:20 Deploy del Proyecto
02:18:08 Outro
Código del Ejemplo:
https://github.com/FaztWeb/flask-postgres-crud-spa
#python #javascript #flask #postgresql
1653625169
En este ejemplo practico de Django aprenderás a conectar una aplicación web a una base de datos como lo es PostgreSQL, para poder hacer las operaciones CRUD (Create, Read, Update. Delete) típicas.
Índice del Contenido:
00:00 Introducción del Contenido
01:15 Project Setup - Conexion a PostgreSQL
17:08 Vista de Tareas
23:44 Static files
27:11 Crear Tareas
38:21 Listar tareas
44:05 Eliminar Tareas
51:39 Bootstrap5
Código del Ejemplo:
https://github.com/FaztWeb/djangocrud_postgresql
#django #python #postgresql
1653277306
In this Node Express PostgreSQL tutorial, we will use only the pg module only to access the PostgreSQL database. So, it will be faster instead of using ORM such as Sequelize.js which was introduced in our previous tutorial. But, we need more effort to create a PostgreSQL table and write SQL in our Express application.
This tutorial is divided into several steps:
Step #1: Setup PostgreSQL Database and Tables
Step #2: Create Express.js Application
Step #3: Create REST Controller
Step #4: Create a Router
Step #5: Run and Test Node Express PostgreSQL using Postman
Full articles
https://www.djamware.com/post/626e00ade9d85587effcba87/node-express-postgresql-faster-crud-rest-api
Full source codes
https://github.com/didinj/node-express-pg-postgresql-rest-api.git
#node #express #restapi #postgresql #api
1652947771
The much anticipated build is FINALLY HERE!
Join me as I build the Reddit 2.0 CLONE with REACT & NEXT.js, you'll learn how to do the following in this build:
👉 You’ll learn how to create a GraphQL backend directly connected to your PostgreSQL Supabase database effortlessly with Stepzen!
👉 You’ll be able to build a Login authentication flow with the Reddit API using NextAuth
👉 You’ll learn how to implement your first SQL relational database (Including how to use Primary & Foreign Keys)!
👉 You’ll learn how to write robust code with Typescript!
👉 You’ll learn how to leverage Next.js Server Side Rendering to get a FASTER page load time!
👉 You’ll learn to create your own API backend endpoints to communicate safely with your frontend!
👉 You’ll learn about Tailwind CSS and how to build this awesome Responsive website!
👉 You’ll be able to Deploy to Vercel and have the site online by the end of this tutorial!
+ SO MUCH MORE!
🖥️ CODE
Get the code for my builds here: https://links.papareact.com/github
🕐 TIMESTAMPS:
[COMING SOON]
#reactjs #nextjs #typescript #tailwindcss #postgresql #sql #databases #stepzen #graphql #supabase
1652847033
There are a lot of different SQL options to choose from, but which one is right for you? In this video we take a high level look at the similarities and differences between these types of SQL.
0:00 Intro
1:14 High Level Comparison
3:44 MySQL User Interface and Features
5:43 Microsoft SQL Server User Interface and Features
10:08 Postgresql User Interface and Features
12:55 Overall Thoughts and Recommendations
SQL Server, PostgreSQL, MySQL... what's the difference? Where do I start?
In this tutorial, you'll learn some of the basic differences between SQL dialects and where you should begin.
A relational database is a set of tables (datasets with rows and columns) that contain information relating to other tables in the database.
The diagram below contains information about columns in two tables in an example relational database. Both tables contain columns named customer_id, which establishes a relationship between the tables. As the company grows and records thousands (or millions) of orders, storing data in separate tables helps optimize for space and reduce the size of the database.
SQL, or Structured Query Language, is the standard language for interacting with relational databases. With SQL, you can query, or ask questions of, the data in a relational database. Working with SQL and relational databases is an invaluable skill set for a data analyst, data engineer, or a data scientist.
If you have started looking for ways to learn SQL, you may have noticed the many different dialects of SQL available to learn with some clear (and less clear) distinctions between the different dialects. So where do you begin? Which version of SQL is most helpful to you if you haven’t used it before? In this article, we will focus on four of the most popular database management systems -- PostgreSQL, MySQL, SQLite, and SQL Server -- and their versions of SQL syntax.
The graph below from Stack Overflow Trends provides a sense of how often each of these platforms is discussed -- each line represents the percentage of all Stack Overflow questions about each version of SQL.
MySQL has consistently been the most popular version of SQL in Stack Overflow questions. Second in line is Microsoft SQL Server (including T-SQL, the name of Microsoft’s dialect of SQL), which remains a consistently more popular tag than PostgreSQL and SQLite. This means that if you have a question specific to one of these systems, you’re more likely to find that someone already asked your question.
PostgreSQL, MySQL, and SQLite use very similar syntax, with some notable differences highlighted below. Microsoft SQL Server has the greatest contrast in SQL syntax, as well as a wide variety of functions not available in other platforms. The table below highlights some examples of basic differences between SQL platforms.
SQL Server | MySQL | PostgreSQL | SQLite | |
---|---|---|---|---|
SELECT ... | Select [col1], [col2] | SELECT col1, col2 | SELECT col1, col2 | SELECT col1, col2 |
Data from tables is case sensitive? | Yes WHERE name = ‘John’ Or WHERE name = ‘john’ are not the same | No WHERE name = ‘John’ Or WHERE name = ‘john’ are the same | Yes WHERE name = ‘John’ Or WHERE name = ‘john’ are not the same | Yes WHERE name = ‘John’ Or WHERE name = ‘john’ are not the same |
Using quotation marks | name = ‘John’ only | name = ‘John’ or name = “John” | name = ‘John’ only | name = ‘John’ or name = “John” |
Aliases for columns and tables | SELECT AVG(col1)=avg1 | SELECT AVG(col1) AS avg1 | SELECT AVG(col1) AS avg1 | SELECT AVG(col1) AS avg1 |
Working with dates | GETDATE() DATEPART() | CURDATE() CURTIME() EXTRACT() | CURRENT_DATE() CURRENT_TIME() EXTRACT() | DATE(‘now’) strftime() |
Window functions i.e., OVER(), PARTITION BY() | Yes | Yes | Yes | No (need to use subqueries instead) |
For students who have little to no experience with SQL and are looking to gain the most broadly applicable skills, I recommend starting with PostgreSQL. Despite the overwhelming popularity of MySQL, PostgreSQL may be a better choice because its syntax most closely conforms to Standard SQL. This means that you can easily translate your skills to other database management systems such as MySQL or SQLite. For example, the query below aggregates data from a database of sales information. It contains a join, an aggregate function, and a filter. This syntax will generate identical results in all three database systems.
Select
c.customer_name,
SUM(p.amount) AS total_sales
FROM customers AS c
LEFT JOIN purchases AS p
ON c.customers_id = p.customer_id
WHERE
c.customer_location = 'USA'
GROUP BY
c.customer_name;
If you anticipate working with Microsoft SQL Server in your career, I recommend you start by learning T-SQL/Microsoft SQL. SQL Server continues to maintain a sizable market share and is an important database management system in many industries. If you are unsure which of these two is more important for you, I recommend browsing through job openings in your field to determine if there is a preference for a specific database system in specific roles or industries.
MySQL Download: https://www.mysql.com/downloads/
MySQL Workbench Download: https://www.mysql.com/products/workbench/
Postgresql Download: https://www.postgresql.org/download/
Pgadmin 4 Download: https://www.pgadmin.org/download/
SQL Server Download: https://www.microsoft.com/en-us/sql-server/sql-server-downloads
SQL Server Management Studio Download: https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver15
#mysql #postgresql #microsoft #sqlserver
1652687507
Aprende a subir tus aplicaciones de Nodejs más bases de datos en Servicios de la nube, de forma gratuita, en este ejemplo aprenderemos a hacer deploy de nuestras aplicaciones de forma sencilla y rapida. Para esto usaremos servicios como Heroku el cual nos permite subir aplicaciones backend escritas en Nodejs (y otros lenguajes de programación); Heroku PostgreSQL el cual nos permite subir nuestras bases de datos de PostgreSQL de forma gratuita, y Mongodb Atlas, el cual es un servicio que nos permite crear un cluster de Mongodb y conectarnos a el de forma sencilla y gratuita.
Heroku
https://www.heroku.com/
Mongodb atlas
https://www.mongodb.com/es/atlas/database
#nodejs #heroku #postgresql #node
1652526300
El código de este tutorial está disponible en mi repositorio de Github . Siéntete libre de clonarlo mientras sigues los pasos. ¡Vamos a empezar!
¿Qué es NestJS?
NestJS es un marco de Node.js para crear aplicaciones del lado del servidor rápidas, comprobables, escalables y poco acopladas que usan TypeScript. Aprovecha los potentes marcos de servidores HTTP como Express o Fastify.
Nest agrega una capa de abstracción a los marcos de Node.js y expone sus API a los desarrolladores. Admite sistemas de gestión de bases de datos como PostgreSQL y MySQL. NestJS también ofrece inyecciones de dependencia Websockets y APIGetaways.
¿Qué es un WebSocket?
Un WebSocket es un protocolo de comunicaciones informáticas que proporciona canales de comunicación full-duplex a través de una única conexión TCP. El IETF estandarizó el protocolo WebSocket como RFC 6455 en 2011.
La especificación actual se conoce como HTML Living Standard. A diferencia de HTTP/HTTPS, Websocket son protocolos con estado, lo que significa que la conexión establecida entre el servidor y el cliente estará viva a menos que el servidor o el cliente la terminen; una vez que una conexión WebSocket se cierra por un extremo, se extiende al otro extremo.
Este tutorial es una demostración práctica. Para seguir, asegúrese de haber instalado lo siguiente:
configuración del proyecto
Antes de sumergirnos en la codificación, configuremos nuestro proyecto NestJS y nuestra estructura de proyecto. Comenzaremos creando la carpeta del proyecto. Luego, abre tu terminal y ejecuta el siguiente comando:
mkdir chatapp && cd chatapp
Creación de la carpeta del proyecto
Luego instale la CLI de NestJS con el siguiente comando:
npm i -g @nestjs/cli
Cuando se complete la instalación, ejecute el siguiente comando para montar un proyecto de NestJS.
nest new chat
Elija su administrador de paquetes npm preferido. Para este tutorial, usaremos npm
y esperaremos a que se instalen los paquetes necesarios. Una vez completada la instalación, instale WebSocket
y Socket.io
con el siguiente comando:
npm i --save @nestjs/websockets @nestjs/platform-socket.io
Luego, cree una aplicación de puerta de enlace con el siguiente comando:
nest g gateway app
Ahora vamos a iniciar nuestro servidor ejecutando el siguiente comando:
npm run start:dev
Configuración de una base de datos de Postgres
Ahora podemos configurar nuestra base de datos de Postgres para almacenar nuestros registros de usuario con la configuración de nuestro servidor.
Primero, usaremos TypeORM (Object Relational Mapper) para conectar nuestra base de datos con nuestra aplicación. Para comenzar, necesitaremos crear una base de datos con los siguientes pasos. Primero, cambie a la cuenta de usuario de Postgres del sistema.
sudo su - postgres
Luego, cree una nueva cuenta de usuario con el siguiente comando.
createuser --interactive
A continuación, cree una nueva base de datos. Puedes hacerlo con el siguiente comando:
createdb chat
Ahora, nos conectaremos a la base de datos que acabamos de crear. Primero, abra el archivo app.module.ts y agregue el siguiente fragmento de código a continuación en la matriz de imports[]
:
...
import { TypeOrmModule } from '@nestjs/typeorm';
import { Chat } from './chat.entity';
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
username: '<USERNAME>',
password: '<PASSWORD>',
database: 'chat',
entities: [Chat],
synchronize: true,
}),
TypeOrmModule.forFeature([Chat]),
],
...
En el fragmento de código anterior, conectamos nuestra aplicación a una base de datos PostgresSQL usando el TypeOrmModule
forRoot
método y pasamos nuestras credenciales de base de datos. Reemplace <USERNAME>
y <PASSWORD>
con el usuario y la contraseña que creó para la base de chat
datos.
Creando nuestra entidad de chat
Ahora que hemos conectado la aplicación a su base de datos, cree una entidad de chat para guardar los mensajes del usuario. Para hacer eso, cree un chat.entity.ts
archivo en la carpeta src y agregue el fragmento de código a continuación:
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
} from 'typeorm';
@Entity()
export class Chat {
@PrimaryGeneratedColumn('uuid')
id: number;
@Column()
email: string;
@Column({ unique: true })
text: string;
@CreateDateColumn()
createdAt: Date;
}
En el fragmento de código anterior, creamos las columnas para nuestros chats usando los decoradores Entity
, Column
, CreatedDateColumn
y PrimaryGenerateColumn
proporcionados por TypeOrm.
Configuración de un socket web
Configuremos una conexión de socket web en nuestro servidor para enviar mensajes en tiempo real. Primero, importaremos el módulo requerido que necesitamos con un fragmento de código a continuación.
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { AppService } from './app.service';
import { Chat } from './chat.entity';
En el fragmento de código anterior, importamos SubscribeMessage()
para escuchar eventos del cliente, WebSocketGateway()
que dará acceso a socket.io; también importamos las instancias OnGatewayInit
, OnGatewayConnection
y .OnGatewayDisconnect
Esta instancia de WebSocket le permite conocer el estado de su aplicación. Por ejemplo, podemos hacer que nuestro servidor haga cosas cuando un servidor se une o se desconecta del chat. Luego importamos la Chat
entidad y la AppService
que expone los métodos que necesitamos para guardar los mensajes de nuestros usuarios.
@WebSocketGateway({
cors: {
origin: '*',
},
})
Para permitir que nuestro cliente se comunique con el servidor, habilitamos CORS al inicializar el archivo WebSocketGateway
.
export class AppGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
constructor(private appService: AppService) {}
@WebSocketServer() server: Server;
@SubscribeMessage('sendMessage')
async handleSendMessage(client: Socket, payload: Chat): Promise<void> {
await this.appService.createMessage(payload);
this.server.emit('recMessage', payload);
}
afterInit(server: Server) {
console.log(server);
//Do stuffs
}
handleDisconnect(client: Socket) {
console.log(`Disconnected: ${client.id}`);
//Do stuffs
}
handleConnection(client: Socket, ...args: any[]) {
console.log(`Connected ${client.id}`);
//Do stuffs
}
}
Luego, en nuestra AppGateWay
clase, implementamos las instancias de WebSocket que importamos anteriormente. Creamos un método constructor y vinculamos nuestro AppService para tener acceso a sus métodos. Creamos una instancia de servidor a partir de los WebSocketServer
decoradores.
Luego creamos un handleSendMessage
uso de la @SubscribeMessage()
instancia y un handleMessage()
método para enviar datos a nuestro lado del cliente.
Cuando se envía un mensaje a esta función desde el cliente, lo guardamos en nuestra base de datos y devolvemos el mensaje a todos los usuarios conectados en nuestro lado del cliente.
También tenemos muchos otros métodos con los que puede experimentar, como afterInit
, que se activa después de que un cliente se ha conectado, handleDisconnect
que se activa cuando un usuario se desconecta. El handleConnection
método comienza cuando un usuario se une a la conexión.
Creación de un controlador/servicio
Ahora vamos a crear nuestro servicio y controlador para guardar el chat y mostrar nuestra página estática. Abra el app.service.ts
archivo y actualice el contenido con el fragmento de código a continuación:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Chat } from './chat.entity';
@Injectable()
export class AppService {
constructor(
@InjectRepository(Chat) private chatRepository: Repository<Chat>,
) {}
async createMessage(chat: Chat): Promise<Chat> {
return await this.chatRepository.save(chat);
}
async getMessages(): Promise<Chat[]> {
return await this.chatRepository.find();
}
}
Luego actualice el app.controller.ts
archivo con el fragmento de código a continuación:
import { Controller, Render, Get, Res } from '@nestjs/common';
import { AppService } from './app.service';
import { Chat } from './chat.entity';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('/chat')
@Render('index')
Home() {
return;
}
@Get('/api/chat')
async Chat(@Res() res) {
const messages = await this.appService.getMessages();
res.json(messages);
}
}
En el fragmento de código anterior, creamos dos rutas para representar nuestra página estática y los mensajes del usuario.
Sirviendo nuestra página estática
Ahora configuremos la aplicación para representar el archivo estático y nuestras páginas. Para hacer eso, implementaremos la representación del lado del servidor. Primero, en su main.ts
archivo, configure la aplicación para archivos de servidor estáticos con el siguiente comando:
async function bootstrap() {
...
app.useStaticAssets(join(__dirname, '..', 'static'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('ejs');
...
}
A continuación, cree una static
y una views
carpeta en su src
directorio. En la carpeta de vistas, cree un index.ejs
archivo y agregue el fragmento de código a continuación:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
<title>Let Chat</title>
</head>
<body>
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand">Lets Chat</a>
</div>
</nav>
<div class="container">
<div class="mb-3 mt-3">
<ul style="list-style: none" id="data-container"></ul>
</div>
<div class="mb-3 mt-4">
<input class="form-control" id="email" rows="3" placeholder="Your Email" />
</div>
<div class="mb-3 mt-4">
<input class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Say something..." />
</div>
</div>
<script src="https://cdn.socket.io/4.3.2/socket.io.min.js"
integrity="sha384-KAZ4DtjNhLChOB/hxXuKqhMLYvx3b5MlT55xPEiNmREKRzeEm+RVPlTnAn0ajQNs"
crossorigin="anonymous"></script>
<script src="app.js"></script>
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</body>
</html>
Para acelerar las cosas en nuestras plantillas, usamos Bootstrap para agregar algunos estilos. Luego agregamos dos campos de entrada y una lista desordenada para mostrar los mensajes del usuario. También incluimos nuestro app.js
archivo que crearemos más adelante en esta sección y un enlace al socket.io
cliente.
Ahora cree un app.js
archivo y agregue el fragmento de código a continuación:
const socket = io('http://localhost:3002');
const msgBox = document.getElementById('exampleFormControlTextarea1');
const msgCont = document.getElementById('data-container');
const email = document.getElementById('email');
//get old messages from the server
const messages = [];
function getMessages() {
fetch('http://localhost:3002/api/chat')
.then((response) => response.json())
.then((data) => {
loadDate(data);
data.forEach((el) => {
messages.push(el);
});
})
.catch((err) => console.error(err));
}
getMessages();
//When a user press the enter key,send message.
msgBox.addEventListener('keydown', (e) => {
if (e.keyCode === 13) {
sendMessage({ email: email.value, text: e.target.value });
e.target.value = '';
}
});
//Display messages to the users
function loadDate(data) {
let messages = '';
data.map((message) => {
messages += ` <li class="bg-primary p-2 rounded mb-2 text-light">
<span class="fw-bolder">${message.email}</span>
${message.text}
</li>`;
});
msgCont.innerHTML = messages;
}
//socket.io
//emit sendMessage event to send message
function sendMessage(message) {
socket.emit('sendMessage', message);
}
//Listen to recMessage event to get the messages sent by users
socket.on('recMessage', (message) => {
messages.push(message);
loadDate(messages);
})
En el fragmento de código anterior, creamos una instancia de socket.io y escuchamos los eventos en nuestro servidor para enviar y recibir un mensaje del servidor. Queremos que los chats antiguos estén disponibles cuando un usuario se una al chat de forma predeterminada. Nuestra aplicación debería verse como la siguiente captura de pantalla:
Visualización de datos de usuario con Arctype
Ahora hemos creado con éxito nuestra aplicación de chat. Primero, veamos los datos de los usuarios con Arctype. Para comenzar, inicie Arctype, haga clic en la pestaña MySQL e ingrese las siguientes credenciales de MySQL, como se muestra en la siguiente captura de pantalla:
Luego, haga clic en la mesa de chat para mostrar los mensajes de chat del usuario, como se muestra en la siguiente captura de pantalla:
Probando la aplicación
Ahora abra la aplicación en dos pestañas o ventanas diferentes e intente enviar un mensaje con una dirección de correo electrónico diferente, como se muestra en la siguiente captura de pantalla:
Además, cuando mira su consola, verá registros cuando un usuario se une y se desconecta del servidor que es manejado por los métodos handleDisconnect
y .handleConnection
Conclusión
A lo largo de este tutorial, hemos explorado cómo crear una aplicación de chat en tiempo real con Nestjs y PostgreSQL. Comenzamos con una breve introducción a Nestjs y WebSockets. Luego creamos una aplicación de demostración para demostrar la implementación. Espero que tengas el conocimiento que buscas. Quizás pueda obtener más información sobre la implementación de WebSocket en la documentación de Nestjs y agregar extender la aplicación.
1652526000
このチュートリアルのコードは、私のGithubリポジトリで入手できます。手順に従って、自由にクローンを作成してください。さぁ、始めよう!
NestJSとは何ですか?
NestJSは、TypeScriptを使用する、高速でテスト可能、スケーラブルな、疎結合のサーバー側アプリケーションを作成するためのNode.jsフレームワークです。ExpressやFastifyなどの強力なHTTPサーバーフレームワークを利用します。
Nestは、Node.jsフレームワークに抽象化レイヤーを追加し、そのAPIを開発者に公開します。PostgreSQLやMySQLなどのデータベース管理システムをサポートしています。NestJSは、依存性注入WebsocketとAPIGetawaysも提供します。
Websocketとは何ですか?
WebSocketは、単一のTCP接続を介して全二重通信チャネルを提供するコンピューター通信プロトコルです。IETFは、2011年にWebSocketプロトコルをRFC6455として標準化しました。
現在の仕様は、HTMLLivingStandardとして知られています。HTTP / HTTPSとは異なり、Websocketはステートフルプロトコルです。つまり、サーバーまたはクライアントによって終了されない限り、サーバーとクライアントの間で確立された接続は有効です。WebSocket接続が一方の端で閉じられると、もう一方の端まで拡張されます。
このチュートリアルは実践的なデモンストレーションです。フォローするには、次のものがインストールされていることを確認してください。
プロジェクトの設定
コーディングに取り掛かる前に、NestJSプロジェクトとプロジェクト構造を設定しましょう。プロジェクトフォルダを作成することから始めます。次に、ターミナルを開き、次のコマンドを実行します。
mkdir chatapp && cd chatapp
プロジェクトフォルダの作成
次に、以下のコマンドを使用してNestJSCLIをインストールします。
npm i -g @nestjs/cli
インストールが完了したら、以下のコマンドを実行してNestJSプロジェクトをスキャフォールディングします。
nest new chat
ご希望のnpmパッケージマネージャーを選択してください。このチュートリアルではnpm
、必要なパッケージがインストールされるのを使用して待機します。インストールが完了したら、以下のコマンドを使用してインストールWebSocket
します。Socket.io
npm i --save @nestjs/websockets @nestjs/platform-socket.io
次に、以下のコマンドを使用してゲートウェイアプリケーションを作成します。
nest g gateway app
次に、以下のコマンドを実行してサーバーを起動しましょう。
npm run start:dev
Postgresデータベースのセットアップ
これで、サーバー設定でユーザーレコードを保存するようにPostgresデータベースを設定できます。
まず、TypeORM(Object Relational Mapper)を使用して、データベースをアプリケーションに接続します。まず、次の手順でデータベースを作成する必要があります。まず、システムのPostgresユーザーアカウントに切り替えます。
sudo su - postgres
次に、以下のコマンドを使用して新しいユーザーアカウントを作成します。
createuser --interactive
次に、新しいデータベースを作成します。次のコマンドでこれを行うことができます。
createdb chat
次に、作成したデータベースに接続します。まず、app.module.tsファイルを開き、次のコードスニペットを次の配列に追加しますimports[]
。
...
import { TypeOrmModule } from '@nestjs/typeorm';
import { Chat } from './chat.entity';
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
username: '<USERNAME>',
password: '<PASSWORD>',
database: 'chat',
entities: [Chat],
synchronize: true,
}),
TypeOrmModule.forFeature([Chat]),
],
...
上記のコードスニペットでは、メソッドを使用してアプリケーションをPostgresSQLデータベースに接続TypeOrmModule
forRoot
し、データベースのクレデンシャルを渡しました。<USERNAME>
データベース用に作成したユーザーと<PASSWORD>
パスワードに置き換えchat
ます。
チャットエンティティの作成
アプリケーションをデータベースに接続したので、チャットエンティティを作成してユーザーのメッセージを保存します。これを行うには、srcフォルダーにファイルを作成し、chat.entity.ts
以下のコードスニペットを追加します。
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
} from 'typeorm';
@Entity()
export class Chat {
@PrimaryGeneratedColumn('uuid')
id: number;
@Column()
email: string;
@Column({ unique: true })
text: string;
@CreateDateColumn()
createdAt: Date;
}
上記のコードスニペットでは、TypeOrmが提供する、、、、およびデコレータを使用してチャットの列を作成しましEntity
た。ColumnCreatedDateColumnPrimaryGenerateColumn
Webソケットのセットアップ
リアルタイムメッセージを送信するために、サーバーにWebソケット接続を設定しましょう。まず、必要なモジュールを以下のコードスニペットでインポートします。
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { AppService } from './app.service';
import { Chat } from './chat.entity';
上記のコードスニペットでは、socket.ioへのアクセスを提供するSubscribeMessage()
クライアントからのイベントをリッスンするためにインポートしました。、、、およびインスタンスWebSocketGateway()
もインポートしました。OnGatewayInitOnGatewayConnectionOnGatewayDisconnect
このWebSocketインスタンスを使用すると、アプリケーションの状態を知ることができます。たとえば、サーバーがチャットに参加したり、チャットから切断したりしたときに、サーバーに処理を実行させることができます。Chat
次に、エンティティとをインポートしましたAppService
。これにより、ユーザーのメッセージを保存するために必要なメソッドが公開されます。
@WebSocketGateway({
cors: {
origin: '*',
},
})
クライアントがサーバーと通信できるようにするために、を初期化することでCORSを有効にしますWebSocketGateway
。
export class AppGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
constructor(private appService: AppService) {}
@WebSocketServer() server: Server;
@SubscribeMessage('sendMessage')
async handleSendMessage(client: Socket, payload: Chat): Promise<void> {
await this.appService.createMessage(payload);
this.server.emit('recMessage', payload);
}
afterInit(server: Server) {
console.log(server);
//Do stuffs
}
handleDisconnect(client: Socket) {
console.log(`Disconnected: ${client.id}`);
//Do stuffs
}
handleConnection(client: Socket, ...args: any[]) {
console.log(`Connected ${client.id}`);
//Do stuffs
}
}
次に、AppGateWay
クラスでは、上記でインポートしたWebSocketインスタンスを実装しました。コンストラクターメソッドを作成し、AppServiceをバインドしてそのメソッドにアクセスできるようにしました。WebSocketServer
デコレータからサーバーインスタンスを作成しました。
次に、インスタンスとメソッドをhandleSendMessage
使用してデータをクライアント側に送信するを作成します。@SubscribeMessage()handleMessage()
クライアントからこの関数にメッセージが送信されると、それをデータベースに保存し、クライアント側で接続されているすべてのユーザーにメッセージを送り返します。
afterInit
クライアントが接続した後にhandleDisconnect
トリガーされる、ユーザーが切断したときにトリガーされるなど、実験できる他の多くの方法もあります。このhandleConnection
メソッドは、ユーザーが接続に参加したときに開始されます。
コントローラ/サービスの作成
次に、チャットを保存して静的ページをレンダリングするためのサービスとコントローラーを作成しましょう。ファイルを開き、app.service.ts
以下のコードスニペットでコンテンツを更新します。
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Chat } from './chat.entity';
@Injectable()
export class AppService {
constructor(
@InjectRepository(Chat) private chatRepository: Repository<Chat>,
) {}
async createMessage(chat: Chat): Promise<Chat> {
return await this.chatRepository.save(chat);
}
async getMessages(): Promise<Chat[]> {
return await this.chatRepository.find();
}
}
app.controller.ts
次に、以下のコードスニペットでファイルを更新します。
import { Controller, Render, Get, Res } from '@nestjs/common';
import { AppService } from './app.service';
import { Chat } from './chat.entity';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('/chat')
@Render('index')
Home() {
return;
}
@Get('/api/chat')
async Chat(@Res() res) {
const messages = await this.appService.getMessages();
res.json(messages);
}
}
上記のコードスニペットでは、静的ページとユーザーのメッセージをレンダリングするための2つのルートを作成しました。
静的ページを提供する
次に、静的ファイルとページをレンダリングするようにアプリケーションを構成しましょう。そのために、サーバー側のレンダリングを実装します。まず、main.ts
ファイルで、次のコマンドを使用して静的サーバーファイルにアプリケーションを構成します。
async function bootstrap() {
...
app.useStaticAssets(join(__dirname, '..', 'static'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('ejs');
...
}
次に、ディレクトリにstatic
とviews
フォルダを作成しますsrc
。ビューフォルダにindex.ejs
ファイルを作成し、以下のコードスニペットを追加します。
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
<title>Let Chat</title>
</head>
<body>
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand">Lets Chat</a>
</div>
</nav>
<div class="container">
<div class="mb-3 mt-3">
<ul style="list-style: none" id="data-container"></ul>
</div>
<div class="mb-3 mt-4">
<input class="form-control" id="email" rows="3" placeholder="Your Email" />
</div>
<div class="mb-3 mt-4">
<input class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Say something..." />
</div>
</div>
<script src="https://cdn.socket.io/4.3.2/socket.io.min.js"
integrity="sha384-KAZ4DtjNhLChOB/hxXuKqhMLYvx3b5MlT55xPEiNmREKRzeEm+RVPlTnAn0ajQNs"
crossorigin="anonymous"></script>
<script src="app.js"></script>
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</body>
</html>
テンプレートの処理を高速化するために、Bootstrapを使用していくつかのスタイルを追加しました。次に、ユーザーのメッセージを表示するために、2つの入力フィールドと順序付けされていないリストを追加しました。app.js
また、このセクションの後半で作成するファイルとsocket.io
クライアントへのリンクも含めました。
次に、ファイルを作成し、app.js
以下のコードスニペットを追加します。
const socket = io('http://localhost:3002');
const msgBox = document.getElementById('exampleFormControlTextarea1');
const msgCont = document.getElementById('data-container');
const email = document.getElementById('email');
//get old messages from the server
const messages = [];
function getMessages() {
fetch('http://localhost:3002/api/chat')
.then((response) => response.json())
.then((data) => {
loadDate(data);
data.forEach((el) => {
messages.push(el);
});
})
.catch((err) => console.error(err));
}
getMessages();
//When a user press the enter key,send message.
msgBox.addEventListener('keydown', (e) => {
if (e.keyCode === 13) {
sendMessage({ email: email.value, text: e.target.value });
e.target.value = '';
}
});
//Display messages to the users
function loadDate(data) {
let messages = '';
data.map((message) => {
messages += ` <li class="bg-primary p-2 rounded mb-2 text-light">
<span class="fw-bolder">${message.email}</span>
${message.text}
</li>`;
});
msgCont.innerHTML = messages;
}
//socket.io
//emit sendMessage event to send message
function sendMessage(message) {
socket.emit('sendMessage', message);
}
//Listen to recMessage event to get the messages sent by users
socket.on('recMessage', (message) => {
messages.push(message);
loadDate(messages);
})
上記のコードスニペットでは、socket.ioインスタンスを作成し、サーバー上のイベントをリッスンして、サーバーとの間でメッセージを送受信しました。ユーザーがデフォルトでチャットに参加するときに、古いチャットを利用できるようにする必要があります。アプリケーションは次のスクリーンショットのようになります。
Arctypeを使用したユーザーデータの表示
これで、チャットアプリケーションが正常に作成されました。まず、Arctypeでユーザーのデータを見てみましょう。開始するには、Arctypeを起動し、[MySQL]タブをクリックして、次のスクリーンショットに示すように、次のMySQLクレデンシャルを入力します。
次に、以下のスクリーンショットに示すように、チャットテーブルをクリックして、ユーザーのチャットメッセージを表示します。
アプリケーションのテスト
次に、2つの異なるタブまたはウィンドウでアプリケーションを開き、下のスクリーンショットに示すように、異なる電子メールアドレスでメッセージを送信してみます。
また、コンソールを見ると、ユーザーがhandleDisconnect
andhandleConnection
メソッドによって処理されるサーバーに参加および切断したときにログが表示されます。
結論
このチュートリアル全体を通して、NestjsとPostgreSQLを使用してリアルタイムチャットアプリケーションを作成する方法を探りました。まず、NestjsとWebSocketの簡単な紹介から始めました。次に、実装を示すデモアプリケーションを作成しました。あなたが求めている知識を得たことを願っています。おそらく、NestjsのドキュメントからWebSocketの実装について詳しく学び、アプリケーションを追加拡張することができます。