Last active
December 21, 2023 17:22
-
-
Save eirnym/afe8afb772a79407300a to your computer and use it in GitHub Desktop.
SQLAlchemy 'if exists' patch
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
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) |
Hey, thank you!
Just enable patches using enable_patches
function and you're all set. it's not the best patch, but works well.
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
Nice work ! but how is it to be used ?