Drop database postgresql python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

andrewp-as-is/django-postgres-dropdb.py

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

$ [sudo] pip install django-postgres-dropdb

example 1 — management command:

INSTALLED_APPS+=['django_postgres_dropdb'] DATABASES = < 'default': < 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASS'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), > >
$ python manage.py dropdb $ python manage.py dropdb "default"

example 2 — python module cli:

DATABASES = < 'default': < 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASS'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), > >
$ export DJANGO_SETTINGS_MODULE=settings $ python -m django_postgres_dropdb $ python -m django_postgres_dropdb "default"

Источник

Simple way to reset Django PostgreSQL database?

I am currently making changes to my models and testing each change. I don’t have any data I need to keep. Is there an easier way than the above to reset the database when migrations donät work?

I would at least like to replace step 2 with something else so that I can skip steps 3-5.

7 Answers 7

Probably the easiest way to do this is to recreate the whole database. In Ubuntu, it looks like this:

sudo su postgres psql drop database your_database_name; create database your_database_name with owner user_you_use_in_django; \q exit 

That’s it. You have clean database. To make it ready to go, you have to run migrations with python manage.py migrate .

If you are working on your project alone, you can delete and recreate migrations, if you want.

Thank you! But that doesn’t simplify the steps in my OP much. I still need to recreate default django users, and still need to alter user roles to what I want them to be.

If you need some data to be present after database recreation, you can use fixtures, or some automation scripts.

from django.db import connection with connection.cursor() as cursor: cursor.execute("DROP SCHEMA public CASCADE;") cursor.execute("CREATE SCHEMA public;") 

I successfully «reset my django postgreSQL database» (while not losing data).

Updating my models.py and then using ./manage.py makemigrations and ./manage.py migrate wasn’t possible because the table(s) I needed to rename pointed to one another circularly. Django was not unable to «auto-magically» accomplish said task.

So, I opted to backup my data. Flush. Delete the tables. Update my models.py file. Modify the (json) backup I created (using ./manage.py datadump > fileName.json ) to reflect my updated column names/table names. Then, I recreated the database using ./manage.py migrate and ./manage.py makemigrations . Then I loaded my backup back into the database’s newly created tables using ./manage.py loaddata fileName.json .

  1. First I took a backup of my server/VM.
  2. ./manage.py dumpdata > db.json
  3. ./manage.py flush
  4. Choose «Yes» [NOTE THIS DELETES ALL YOUR DATA. ]
  5. Delete all tables from —myDataBaseName—
  6. Delete your migrations folder
  7. Make your changes (if you have any) to your model.py file
  8. ./manage.py migrate
  9. ./manage.py makemigrations —myAppName—
  10. ./manage.py migrate —myAppName—
  11. go into db.json and remove contenttype related stuffz. You may also need to remove (and seed manually after step 12 in some cases) auth_permissions related entries in your db.json. Save modified db.json as db_new.json so that you don’t lose your original backup in case things get fubar’d and you need to put everything back to how it was!
  12. ./manage.py loaddata db_new.json

If you are using docker/composer, issue an docker-compose down and then migrate .

This was the right starting place for me! I needed to adapt it a little bit: docker-compose down -v , where the -v means to also delete volumes; docker-compose up —detach db , which is my command to bring the (now empty) database back up; and then the same python manage.py migrate .

If you want a completely clean start, you’re gonna wanna stick to dropping the DB. Which means the steps you mention — recreate it, add privileges, re-generate all the migrations and re-run them.

Good news is that you can easily make all this into a single/few line commands.

Fresh migration files

If you delete the whole folders, you’re gonna have to run the makemigrations command mentioning all the app names. That’s a hassle if you do this often. To have Django see the apps that need migrations, you’ll wanna keep the migrations folder and the __init__.py inside them.

Here’s a bash command for that:

find . -path "*migrations*" -not -regex ".*__init__.py" -a -not -regex ".*migrations" | xargs rm -rf 

Then the usual (this should create migrations for all the apps that had migrations before):

python manage.py makemigrations 

Resetting the PostgreSQL DB

psql -c "drop database ;" psql -c "create database ;" psql -c "grant all on database to ;" 

And then finally re-run migrations with

You’re gonna obviously be missing a superuser, so you might wanna also do:

python manage.py createsuperuser 

No-input way of doing that is piping python code into the shell:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'badmin@myproject.com', 'pa$$w0rd')" | python manage.py shell 

Generally speaking about these very common actions — Do yourself a favour and write a bit of bash. It has saved me many, many accumulated hours over the years of working with not only Django. Because even better than a oneline command is having a whole utility file to store more of these handy functions. Then you can just run something like:

django --reset_migrations db --reset django --migrate 

Or even aggregate that into a single line if you find yourself repeating the same few actions.

reset_django() < find . -path "*migrations*" -not -regex ".*__init__.py" -a -not -regex ".*migrations" | xargs rm -rf python manage.py makemigrations psql -c "drop database ;" psql -c "create database ;" psql -c "grant all on database to ;" python manage.py migrate echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'badmin@myproject.com', 'pa$$w0rd')" | python manage.py shell > 

My utilities for inspiration

#!/bin/bash django() < project_name=$(basename $PWD) project_path="$PWD" manage_path="$/$/manage.py" if [ ! -f $manage_path ] ; then # No project/manage.py echo "Error: Could not locate Django manage.py file." return -1 fi if [ $# -eq 0 ] ; then echo "Django project detected." fi while [ ! $# -eq 0 ] do case "$1" in --help | -h) echo "Django shortcut, unknown commands are forwarded to manage.py" echo " -c, --check Run Django manage.py check." echo " --req Install requirements." echo " -r, --run Run server." echo " -s, --shell Run Django shell plus." echo " -sd, --shell Run Django shell plus. Debug DB (print sql)" echo "" ;; --check | -c) python $manage_path check ;; --shell | -s) python $manage_path shell_plus --bpython ;; --shell | -sd) python $manage_path shell_plus --bpython --print-sql ;; --run | -r) python $manage_path runserver ;; --req) pip install -r $project_path/requirements.txt ;; --mig | -m) python $manage_path makemigrations python $manage_path migrate ;; --reset_migrations) find . -path "*migrations*" -not -regex ".*__init__.py" -a -not -regex ".*migrations" | xargs rm -rf python $manage_path makemigrations ;; *) python $manage_path "$@" ;; esac shift done > 

Источник

postgres — cannot drop database using psycopg2

Alright, fair enough. So I opened a connection to postgres and took a peek at the existing processed before and while my code was running. Before my code started, we get this:

postgres=# select pid from pg_stat_activity 

This command returns a single PID, PID 6052 This process is me, so that’s good. Now here is what I get when query running processes while my python code is running:

 postgres=# select * from pg_stat_activity; datid | datname | pid | usesysid | usename | application_name | client_addr | client_hostname | client_port | backend_start | xact_start | query_start | state_change | waiting | state | query 12029 | postgres | 6052 | 10 | postgres | psql | ::1 | | 49842 | 2014-03-11 23:14:34.049-06 | 2014-03-11 23:14:58.938-06 | 2014-03-11 23:14:58.938-06 | 2014-03-11 23:14:58.938-06 | f | active | select * from pg_stat_activity; 142547 | crowdsurfer | 3952 | 10 | postgres | | 127.0.0.1 | | 49849 | 2014-03-11 23:14:57.489-06 | | 2014-03-11 23:14:57.491-06 | 2014-03-11 23:14:57.491-06 | f | idle | SET default_transaction_isolation TO 'read committed' 12029 | postgres | 7908 | 10 | postgres | | ::1 | | 49851 | 2014-03-11 23:14:57.556-06 | 2014-03-11 23:14:57.559-06 | 2014-03-11 23:14:57.559-06 | 2014-03-11 23:14:57.559-06 | f | active | DROP DATABASE crowdsurfer; (3 rows) 

The python code started 2 processes! One connects to the postgres DB, which I did explicitly. The other connects to the DB I want to delete (crowdsurfer). Note that it is idle, and the query it ran was SET default_transaction_isolation TO ‘read committed’ So it seems like setting conn.autocommit equal to true is creating a new process. Any thoughts on what to do here to make drop this DB?

Источник

Читайте также:  Дженерики это в java
Оцените статью