Лабораторные работы по Postgresql за 5 семестр

Overview

Практикум по Postgresql

ERD для заданий 2.x:

2-1

ERD для заданий 3.x:

3-1

Их делал вот тут

Ниже есть 2 инструкции — по установке postgresql на manjaro и по переносу папки с бд на hdd.

Инструкции, как и лабы, могут содержать ошибки, неточности и т.д., предоставляются по принципу "AS IS" без каких-либо гарантий :)

Удачи!

Установка Postgres 11 на Manjaro

Почему 11? На сайте курса написано, что нужен 11. Думаю, что если использовать самую новую версию, никаких проблем не возникнет. Но я не стал рисковать, поэтому вот гайд:

Ставится больно, но работает.

Ставим AUR-пакет postgresql-11 (требуют 11.x версию)

postgres работает через отдельного пользователя. Особенность — в него нельзя зайти через пароль. Поэтому сделать это может только рут: sudo su postgres (тут уже пароль от рута нужен).

run.sh chmod +x run.sh ./run.sh vim data/postgresql.conf # изменить `unix_socket_directories` на '/tmp' ">
sudo chown postgres:postgres /var/lib/postgres
sudo su postgres
cd
initdb -D data
echo "pg_ctl -D data/ -l logfile start" > run.sh
chmod +x run.sh
./run.sh
vim data/postgresql.conf # изменить `unix_socket_directories` на '/tmp'

PgAdmin4

Ставится как pip-пакет. По-другому не работает, я очень долго мучился с этим.

sudo mkdir /var/lib/pgadmin /var/log/pgadmin
pip install pgadmin4
sudo chown greedisgood:greedisgood /var/lib/pgadmin

pgadmin4

Каждый раз нужно будет запускать сервак так:

sudo su postgres
cd
./run.sh
<ctrl+D>
pgadmin4

В Pgadmin4 подключиться к серверу с хостом localhost и дефолтным портом. Пароль у меня был пустой.

Запросы пишем через query tool к конкретной бд. В теме про транзакции надо использовать два query tool параллельных, выключить auto-commit, выделять мышкой нужные строки. Тогда при нажатии f5 будут выполняться только они.

Перенос кластера бд на HDD для лаб 3.x

Чтобы не создавать 20-50 Гб активно использующихся данных на ssd, можно перенести папку с данными постгреса на hdd. Предполагается, что система у вас на ssd.

Если жёсткий диск имеет файловую систему NTFS и вы на Linux, придётся немного повозиться, потому что при дефолтном монтировании NTFS в Linux права тупо не работают, а postgres требует, чтобы права на папку с данными были 0700 — исключительно для владельца (юзера postgres)

В /etc/fstab добавьте следующую строку в конец:

UUID=E8B4580DB457DC9E /mnt/Data ntfs auto,users,permissions 0 0

Здесь вместо E8B4580DB457DC9E надо указать UUID вашего раздела диска. Узнать его можно в GParted (или через какую-нибудь консольную утилиту)

Сохраняем файл, выходим.

Дальше перезагружаемся и пишем в терминале

run.sh chmod +x run.sh ./run.sh ">
sudo mkdir -p /mnt/Data/psql-data
sudo su postgres
cd
echo "pg_ctl -D /mnt/Data/psql-data/ -l logfile start" > run.sh
chmod +x run.sh
./run.sh

Если pg_ctl не найден, то в run.sh меняем pg_ctl на полный путь, который можно узнать через find /usr/lib/postgresql/ -name pg_ctl. Вообще так делать, вроде как, не стоит, но оно работает.

Если сервер не стартует, читаем /var/lib/postgres/logfile. Скорее всего надо будет что-то поправить в /mnt/Data/psql-data/postgresql.conf

Каждый раз нужно будет запускать сервак так:

sudo su postgres
cd
./run.sh

Ну и в Pgadmin4 подключиться к localhost:<порт из /mnt/Data/psql-data/postgresql.conf>

Куда кидать файлы с данными

Чтобы обойти приколы с правами на файл и генерить его из-под обычного юзера, файлы мы будем хранить в /mnt/Data:

-rw-r--r— 1 greedisgood greedisgood 8340763194 окт 24 19:37 users.csv

(это вывод ls -la, который показывает, что владелец файла — обычный юзер)

Дальше создадим символическую ссылку внутри psql-data:

sudo su postgres
cd /mnt/Data/psql-data
ln -s ../users.csv users.csv

Всё. Теперь символическая ссылка будет указывать на нужный нам файл, и всё будет работать. В аргументах команды COPY в скриптах нужно писать просто 'users.csv'.

Owner
Danila
MSU student
Danila
Simple json type database for python3

What it is? Simple json type database for python3! What about speed? The speed is great! All data is stored in RAM until saved. How to install? pip in

3 Feb 11, 2022
A Persistent Embedded Graph Database for Python

Cog - Embedded Graph Database for Python cogdb.io New release: 2.0.5! Installing Cog pip install cogdb Cog is a persistent embedded graph database im

Arun Mahendra 214 Dec 30, 2022
A fast ordered NoSQL database.

MerkavaDB Note This is still in active development. Things will change. If you are interested in helping out, or would like to see any particular feat

Adam Hopkins 6 Sep 29, 2022
Python function to query SQLite files stored on S3

sqlite-s3-query Python function to query a SQLite file stored on S3. It uses multiple HTTP range requests per query to avoid downloading the entire fi

Michal Charemza 189 Dec 27, 2022
ChaozzDBPy - A python implementation based on the original ChaozzDB from Chaozznl with some new features

ChaozzDBPy About ChaozzDBPy is a python implementation based on the original Cha

Igor Iglesias 1 May 25, 2022
Turn SELECT queries returned by a query into links to execute them

datasette-query-links Turn SELECT queries returned by a query into links to execute them Installation Install this plugin in the same environment as D

Simon Willison 5 Apr 27, 2022
Manage your sqlite database very easy (like django) ...

Manage your sqlite database very easy (like django) ...

aWolver 1 Feb 09, 2022
TinyDB is a lightweight document oriented database optimized for your happiness :)

Quick Links Example Code Supported Python Versions Documentation Changelog Extensions Contributing Introduction TinyDB is a lightweight document orien

Markus Siemens 5.6k Dec 30, 2022
This is a simple graph database in SQLite, inspired by

This is a simple graph database in SQLite, inspired by "SQLite as a document database".

Denis Papathanasiou 1.2k Jan 03, 2023
A NoSQL database made in python.

CookieDB A NoSQL database made in python.

cookie 1 Nov 30, 2022
Tools for analyzing Git history using SQLite

git-history Tools for analyzing Git history using SQLite Installation Install this tool using pip: $ pip install git-history Usage This tool can be r

Simon Willison 128 Jan 02, 2023
A super easy, but really really bad DBMS

Dumb DB Are you looking for a reliable database management system? Then you've come to the wrong place. This is a very small database management syste

Elias Amha 5 Dec 28, 2022
Postgres full text search options (tsearch, trigram) examples

postgres-full-text-search Postgres full text search options (tsearch, trigram) examples. Create DB CREATE DATABASE ftdb; To feed db with an example

Jarosław Orzeł 97 Dec 30, 2022
Python function to extract all the rows from a SQLite database file while iterating over its bytes, such as while downloading it

Python function to extract all the rows from a SQLite database file while iterating over its bytes, such as while downloading it

Department for International Trade 16 Nov 09, 2022
Metrics-advisor - Analyze reshaped metrics from TiDB cluster Prometheus and give some advice about anomalies and correlation.

metrics-advisor Analyze reshaped metrics from TiDB cluster Prometheus and give some advice about anomalies and correlation. Team freedeaths mashenjun

3 Jan 07, 2022
Codeqlcompile - 自动反编译闭源应用,创建codeql数据库

codeql_compile 自动反编译闭源应用,创建codeql数据库 准备 首先下载ecj.jar和idea提供反编译的java-decompiler.ja

236 Jan 05, 2023
ClutterDB - Extremely simple JSON database made for infrequent changes which behaves like a dict

extremely simple JSON database made for infrequent changes which behaves like a dict this was made for ClutterBot

Clutter Development 1 Jan 12, 2022
A very simple document database

DockieDb A simple in-memory document database. Installation Build the Wheel Fork or clone this repository and run python setup.py bdist_wheel in the r

1 Jan 16, 2022
HTTP graph database built in Python 3

KiwiDB HTTP graph database built in Python 3. Reference Format References are strings in the format: { JanCraft 1 Dec 17, 2021

Monty, Mongo tinified. MongoDB implemented in Python !

Monty, Mongo tinified. MongoDB implemented in Python ! Was inspired by TinyDB and it's extension TinyMongo

David Lai 523 Jan 02, 2023