Лабораторные работы по 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
LaikaDB, banco de dados para projetos simples.

LaikaDB LaikaDB é um banco de dados noSQL para uso local e simples, onde você pode realizar gravações e leituras de forma eficiente e simples. Todos o

Jaedson Silva 0 Jun 24, 2022
Makes google's political ad database actually useful

Making Google's political ad transparency library suck less This is a series of scripts that takes Google's political ad transparency data and makes t

The Guardian 7 Apr 28, 2022
Decentralised graph database management system

Decentralised graph database management system To get started clone the repo, and run the command below. python3 database.py Now, create a new termina

Omkar Patil 2 Apr 18, 2022
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
EmployeeDB - Advanced Redis search functionalities on Python applied on an Employee management backend app

EmployeeDB - Advanced Redis search functionalities on Python applied on an Employee management backend app

Ahmad Bazzi 58 Oct 10, 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
A Python wrapper API for operating and working with the Neo4j Graph Data Science (GDS) library

gdsclient This repo hosts the sources for gdsclient, a Python wrapper API for operating and working with the Neo4j Graph Data Science (GDS) library. g

Neo Technology 101 Jan 05, 2023
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
Connect Django Project to PostgreSQL

An application for learning things with creating quizzes and flashcards.Django, PostgresSQL are used for this project.

Cena Ashoori 1 Jan 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
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
MyReplitDB - the most simplistic and easiest wrapper to use for replit's database system.

MyReplitDB is the most simplistic and easiest wrapper to use for replit's database system. Installing You can install it from the PyPI Or y

kayle 4 Jul 03, 2022
Code for a db backend that relies on bash tools (grep, cat, echo, etc)

Simple-nosql-db is a python backend for a database that relies on unix tools such as cat, echo and grep. Funny enough I got the idea from this discuss

Sebastian Alonso 10 Aug 13, 2019
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 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
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
Oh-My-PickleDB is an open source key-value store using Python's json module.

OH-MY-PICKLEDB oh-my-pickleDB is a lightweight, fast, and intuitive data manager written in python 📝 Table of Contents About Getting Started Deployme

Adrián Toral 6 Feb 20, 2022
This repo contains the backend of the KMK project

KMK Backend This repository contains the backend part of the KMK project Demo Watch it on Youtube Getting started Pre-commit hooks After you cloned th

21 Nov 26, 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

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