Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@eirnym
Last active December 21, 2023 17:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eirnym/afe8afb772a79407300a to your computer and use it in GitHub Desktop.
Save eirnym/afe8afb772a79407300a to your computer and use it in GitHub Desktop.
SQLAlchemy 'if exists' patch
import re
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import CreateTable, DropTable, \
CreateSequence, DropSequence, CreateIndex, DropIndex
from sqlalchemy.dialects.postgresql import DropEnumType
patches = (
(CreateTable, 'visit_create_table', "^\s*CREATE TABLE", "CREATE TABLE IF NOT EXISTS"),
(CreateIndex, 'visit_create_index', "^\s*CREATE INDEX", "CREATE INDEX IF NOT EXISTS"),
(DropTable, 'visit_drop_table', "^\s*DROP TABLE", "DROP TABLE IF EXISTS"),
(DropSequence, 'visit_drop_sequence', "^\s*DROP SEQUENCE", "DROP SEQUENCE IF EXISTS"),
(DropIndex, 'visit_drop_index', "^\s*DROP INDEX", "DROP INDEX IF EXISTS"),
(DropEnumType, 'visit_drop_enum_type', "^\s*DROP TYPE", "DROP TYPE IF EXISTS"),
)
def create_patch(visitor, method, re_from, re_to, if_always=False):
@compiles(visitor)
def _if_exists_(element, compiler, **kw):
output = getattr(compiler, method)(element, **kw)
if if_always or element.element.info.get('ifexists'):
output = re.sub(re_from, re_to, output, re.S)
return output
return _if_exists_
def enable_patches(if_always=False):
for patch in patches:
create_patch(*patch, if_always=if_always)
@obonyojimmy
Copy link

Hey, thank you!

Just enable patches using enable_patches function and you're all set. it's not the best patch, but works well.

Thanks , but how do i import the function ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment