Skip to content

Instantly share code, notes, and snippets.

@liquidgenius
Last active May 23, 2021 15:58
Show Gist options
  • Save liquidgenius/07f080b199dc8377b64e268517bbf897 to your computer and use it in GitHub Desktop.
Save liquidgenius/07f080b199dc8377b64e268517bbf897 to your computer and use it in GitHub Desktop.
A Masonite 3 ORM helper to get the names of the columns irrespective of the database flavor SQLite, MySQL, Postgres. Pass any model to the function. Usage details provided in function. https://orm.masoniteproject.com/
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://orm.masoniteproject.com/
# app.helpers.columns.py
from config.database import DB
from masoniteorm.collection import Collection
def columns(model):
""" Return any model's associated table's columns as a collection. Care is taken to minimize any effects on a
Production table. If records exist on a table, the first records keys are simply extracted. If no records exist,
a model is hydrated with an empty dictionary in memory, then inside a transaction, saved to the associated table.
After finding that record and stripping it's keys, the transaction is rolled back, leaving the table empty again.
This process should be safe for Production environments as it does not make any lasting alterations to tables that
contain data.
Parameters
----------
model: from masoniteorm.models.Model: Any valid model inheriting from masonite base Model.
Usage
-----
from app.helpers.columns import columns
# Empty Table
column_names = columns(Model)
print(column_names.serialize())
# Add a null record
Model.hydrate({}).save()
# Populated Table
column_names = columns(Model)
print(column_names.serialize())
Returns
-------
result: masoniteorm.collections.Collection: A collection of column names of the table associated with the model.
"""
# A result means there are records in the table; strip keys of first record.
if model.first():
result = list(model.find(1).serialize().keys())
# No result means starting with and leaving the table empty. Inside a transaction, strip the keys of an empty record
# then roll back the transaction. It appears the transaction does not actually need to be committed.
else:
DB.begin_transaction()
result = list(model.hydrate({}).save().find(1).serialize().keys())
DB.rollback()
# Return a collection of column names in order of the table schema
return Collection(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment