Created
January 1, 2018 17:24
-
-
Save ContrastingSounds/c1db3bd7dcea94693c52ed1805552b38 to your computer and use it in GitHub Desktop.
Shows how to dynamically create a database schema using SQLAlchemy and a table schema stored in a Python dictionary. For completeness, includes creating the original database (in this case using PostgreSQL).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### PostgreSQL DB Creation" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import json\n", | |
"\n", | |
"from psycopg2 import connect\n", | |
"from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT" | |
] | |
}, | |
{ | |
"cell_type": "raw", | |
"metadata": {}, | |
"source": [ | |
"{'dbname': 'postgres',\n", | |
" 'host': 'localhost',\n", | |
" 'password': '********',\n", | |
" 'port': '5432',\n", | |
" 'user': '********'}" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"with open('psql_local_creds.json', 'r') as file:\n", | |
" creds = json.loads(file.read())" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"conn = connect(**creds)\n", | |
"\n", | |
"new_dbname = 'newdb'\n", | |
"\n", | |
"conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n", | |
"with conn.cursor() as cursor:\n", | |
" cursor.execute(f'CREATE DATABASE {new_dbname}')\n", | |
" cursor.execute(f'GRANT ALL PRIVILEGES ON DATABASE {new_dbname} TO {creds[\"user\"]}')" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### SQLAlchemy" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 4, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"from sqlalchemy import create_engine, Table, Column, Integer, String, Float, MetaData\n", | |
"\n", | |
"# Connection string will look like this:\n", | |
"# postgresql+psycopg2://username:password@localhost/newdb\n", | |
"conn_string = f\"postgresql+psycopg2://{creds['user']}:{creds['password']}@{creds['host']}/{new_dbname}\"\n", | |
"\n", | |
"engine = create_engine(conn_string, echo=False)\n", | |
"metadata = MetaData()" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 5, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"schema = {\n", | |
" 'dimensions': ['field_one', 'field_two'],\n", | |
" 'integers': ['int_one', 'int_two'],\n", | |
" 'floats': ['only_float'],\n", | |
"}\n", | |
"\n", | |
"\n", | |
"columns = [Column(column, String) for column in schema['dimensions']]\n", | |
"columns += [Column(column, Integer) for column in schema['integers']]\n", | |
"columns += [Column(column, Float) for column in schema['floats']]\n", | |
"\n", | |
"table = Table('my_table', metadata, *columns)\n", | |
"\n", | |
"metadata.drop_all(engine)\n", | |
"metadata.create_all(engine)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### Validate table" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 6, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"%load_ext sql\n", | |
"%config SqlMagic.autopandas=True" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 7, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": [ | |
"'Connected: vgadmin@newdb'" | |
] | |
}, | |
"execution_count": 7, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"%sql $conn_string" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 8, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
" * postgresql+psycopg2://vgadmin:ttsms123@localhost/newdb\n", | |
" * vgadmin@newdb\n", | |
"1 rows affected.\n" | |
] | |
}, | |
{ | |
"data": { | |
"text/html": [ | |
"<div>\n", | |
"<style scoped>\n", | |
" .dataframe tbody tr th:only-of-type {\n", | |
" vertical-align: middle;\n", | |
" }\n", | |
"\n", | |
" .dataframe tbody tr th {\n", | |
" vertical-align: top;\n", | |
" }\n", | |
"\n", | |
" .dataframe thead th {\n", | |
" text-align: right;\n", | |
" }\n", | |
"</style>\n", | |
"<table border=\"1\" class=\"dataframe\">\n", | |
" <thead>\n", | |
" <tr style=\"text-align: right;\">\n", | |
" <th></th>\n", | |
" </tr>\n", | |
" </thead>\n", | |
" <tbody>\n", | |
" </tbody>\n", | |
"</table>\n", | |
"</div>" | |
], | |
"text/plain": [ | |
"Empty DataFrame\n", | |
"Columns: []\n", | |
"Index: []" | |
] | |
}, | |
"execution_count": 8, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"%sql INSERT INTO my_table VALUES ('a', 'b', 1, 2, 3.3)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 9, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
" * postgresql+psycopg2://vgadmin:ttsms123@localhost/newdb\n", | |
" * vgadmin@newdb\n", | |
"1 rows affected.\n" | |
] | |
} | |
], | |
"source": [ | |
"df = %sql SELECT * FROM my_table" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 10, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/html": [ | |
"<div>\n", | |
"<style scoped>\n", | |
" .dataframe tbody tr th:only-of-type {\n", | |
" vertical-align: middle;\n", | |
" }\n", | |
"\n", | |
" .dataframe tbody tr th {\n", | |
" vertical-align: top;\n", | |
" }\n", | |
"\n", | |
" .dataframe thead th {\n", | |
" text-align: right;\n", | |
" }\n", | |
"</style>\n", | |
"<table border=\"1\" class=\"dataframe\">\n", | |
" <thead>\n", | |
" <tr style=\"text-align: right;\">\n", | |
" <th></th>\n", | |
" <th>field_one</th>\n", | |
" <th>field_two</th>\n", | |
" <th>int_one</th>\n", | |
" <th>int_two</th>\n", | |
" <th>only_float</th>\n", | |
" </tr>\n", | |
" </thead>\n", | |
" <tbody>\n", | |
" <tr>\n", | |
" <th>0</th>\n", | |
" <td>a</td>\n", | |
" <td>b</td>\n", | |
" <td>1</td>\n", | |
" <td>2</td>\n", | |
" <td>3.3</td>\n", | |
" </tr>\n", | |
" </tbody>\n", | |
"</table>\n", | |
"</div>" | |
], | |
"text/plain": [ | |
" field_one field_two int_one int_two only_float\n", | |
"0 a b 1 2 3.3" | |
] | |
}, | |
"execution_count": 10, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"df" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.6.3" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment