# Path: statik/common.py
# class ContentLoadable(object):
#     """Can provide functionality like the YamlLoadable class, but also supports
#     loading content and metadata from a Markdown file.
#     """
#     def __init__(self, filename=None, file_type=None, from_string=None, from_dict=None,
#             name=None, markdown_config=None, encoding='utf-8', error_context=None):
#         self.vars = None
#         self.content = None
#         self.file_content = None
#         self.file_type = file_type
#         self.error_context = error_context or StatikErrorContext()
#         self.error_context.update(filename=filename)
# 
#         if self.file_type is not None:
#             if self.file_type not in ['yaml', 'markdown']:
#                 raise InternalError(
#                     "Invalid file type for content loadable: %s" % self.file_type,
#                     context=self.error_context
#                 )
# 
#         self.markdown_config = markdown_config
#         self.encoding = encoding
# 
#         if filename is not None:
#             self.filename = filename
# 
#             if self.file_type is None:
#                 ext = list(os.path.splitext(self.filename))[1].lstrip('.')
#                 if ext not in ['yml', 'yaml', 'md', 'markdown']:
#                     raise StatikError(
#                         message="The supplied file is not a YAML or Markdown-formatted file.",
#                         context=self.error_context
#                     )
#                 self.file_type = 'yaml' if (ext in ['yml', 'yaml']) else 'markdown'
# 
#             with open(self.filename, mode='rt', encoding=self.encoding) as f:
#                 self.file_content = f.read()
# 
#         elif from_string is not None:
#             self.filename = None
#             self.file_content = from_string
# 
#         elif from_dict is not None:
#             self.filename = None
#             self.vars = from_dict
# 
#         else:
#             raise MissingParameterError(
#                 "filename", "from_string", "from_dict",
#                 context=self.error_context
#             )
# 
#         if name is not None:
#             self.name = name
#         elif self.filename is not None:
#             self.name = extract_filename(self.filename)
#         else:
#             raise MissingParameterError(
#                 "name", "filename",
#                 context=self.error_context
#             )
# 
#         # if it wasn't loaded from a dictionary
#         if self.vars is None:
#             if self.file_type is None:
#                 raise MissingParameterError(
#                     "file_type",
#                     context=self.error_context
#                 )
# 
#             # if it's a YAML file
#             if self.file_type == 'yaml':
#                 self.vars = yaml.safe_load(self.file_content) if self.file_content else {}
#                 if not isinstance(self.vars, dict):
#                     self.vars = {}
#             else:
#                 markdown_ext = [
#                     MarkdownYamlMetaExtension(),
#                     MarkdownLoremIpsumExtension(error_context=self.error_context)
#                 ]
#                 if self.markdown_config.enable_permalinks:
#                     markdown_ext.append(
#                         MarkdownPermalinkExtension(
#                             permalink_text=self.markdown_config.permalink_text,
#                             permalink_class=self.markdown_config.permalink_class,
#                             permalink_title=self.markdown_config.permalink_title,
#                         )
#                     )
#                 markdown_ext.extend(self.markdown_config.extensions)
# 
#                 md = Markdown(
#                     extensions=markdown_ext,
#                     extension_configs=self.markdown_config.extension_config
#                 )
#                 self.content = md.convert(self.file_content)
#                 self.vars = md.meta
# 
#         if isinstance(self.vars, dict):
#             self.vars = dict_strip(self.vars)
# 
# Path: statik/config.py
# class StatikConfig(YamlLoadable):
#     def __init__(self, *args, **kwargs):
#     def __repr__(self):


from io import open
from sqlalchemy import String, Integer, Column, Table, ForeignKey, \
    Boolean, DateTime, Text, create_engine
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.query import Query
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import close_all_sessions
from dateutil.parser import parse as dateutil_parse
from statik.common import ContentLoadable
from statik.fields import *
from statik.errors import *
from statik.utils import *
from statik.config import MarkdownConfig
from statik.pagination import *
from datetime import datetime, date, timedelta, time
from sqlalchemy import func, distinct
import os.path
import yaml
import mlalchemy
import sqlalchemy
import math
import logging
            )

        if isinstance(query, dict):
            logger.debug("Executing query in safe mode (MLAlchemy)")
            return mlalchemy.parse_query(query).to_sqlalchemy(self.session, self.tables).all()
        else:
            logger.debug("Executing unsafe query (Python exec())")
            if additional_locals is not None:
                for k, v in additional_locals.items():
                    locals()[k] = v

            exec(
                compile(
                    'result = %s' % query.strip(),
                    '<string>',
                    'exec'
                ),
                globals(),
                locals()
            )
            return locals()['result']

    def shutdown(self):
        """Shuts down the database engine."""
        close_all_sessions()
        self.engine.dispose()
        # clear all tracked global variables
        clear_tracked_globals()



# Path: statik/common.py
# class ContentLoadable(object):
#     """Can provide functionality like the YamlLoadable class, but also supports
#     loading content and metadata from a Markdown file.
#     """
#     def __init__(self, filename=None, file_type=None, from_string=None, from_dict=None,
#             name=None, markdown_config=None, encoding='utf-8', error_context=None):
#         self.vars = None
#         self.content = None
#         self.file_content = None
#         self.file_type = file_type
#         self.error_context = error_context or StatikErrorContext()
#         self.error_context.update(filename=filename)
# 
#         if self.file_type is not None:
#             if self.file_type not in ['yaml', 'markdown']:
#                 raise InternalError(
#                     "Invalid file type for content loadable: %s" % self.file_type,
#                     context=self.error_context
#                 )
# 
#         self.markdown_config = markdown_config
#         self.encoding = encoding
# 
#         if filename is not None:
#             self.filename = filename
# 
#             if self.file_type is None:
#                 ext = list(os.path.splitext(self.filename))[1].lstrip('.')
#                 if ext not in ['yml', 'yaml', 'md', 'markdown']:
#                     raise StatikError(
#                         message="The supplied file is not a YAML or Markdown-formatted file.",
#                         context=self.error_context
#                     )
#                 self.file_type = 'yaml' if (ext in ['yml', 'yaml']) else 'markdown'
# 
#             with open(self.filename, mode='rt', encoding=self.encoding) as f:
#                 self.file_content = f.read()
# 
#         elif from_string is not None:
#             self.filename = None
#             self.file_content = from_string
# 
#         elif from_dict is not None:
#             self.filename = None
#             self.vars = from_dict
# 
#         else:
#             raise MissingParameterError(
#                 "filename", "from_string", "from_dict",
#                 context=self.error_context
#             )
# 
#         if name is not None:
#             self.name = name
#         elif self.filename is not None:
#             self.name = extract_filename(self.filename)
#         else:
#             raise MissingParameterError(
#                 "name", "filename",
#                 context=self.error_context
#             )
# 
#         # if it wasn't loaded from a dictionary
#         if self.vars is None:
#             if self.file_type is None:
#                 raise MissingParameterError(
#                     "file_type",
#                     context=self.error_context
#                 )
# 
#             # if it's a YAML file
#             if self.file_type == 'yaml':
#                 self.vars = yaml.safe_load(self.file_content) if self.file_content else {}
#                 if not isinstance(self.vars, dict):
#                     self.vars = {}
#             else:
#                 markdown_ext = [
#                     MarkdownYamlMetaExtension(),
#                     MarkdownLoremIpsumExtension(error_context=self.error_context)
#                 ]
#                 if self.markdown_config.enable_permalinks:
#                     markdown_ext.append(
#                         MarkdownPermalinkExtension(
#                             permalink_text=self.markdown_config.permalink_text,
#                             permalink_class=self.markdown_config.permalink_class,
#                             permalink_title=self.markdown_config.permalink_title,
#                         )
#                     )
#                 markdown_ext.extend(self.markdown_config.extensions)
# 
#                 md = Markdown(
#                     extensions=markdown_ext,
#                     extension_configs=self.markdown_config.extension_config
#                 )
#                 self.content = md.convert(self.file_content)
#                 self.vars = md.meta
# 
#         if isinstance(self.vars, dict):
#             self.vars = dict_strip(self.vars)
# 
# Path: statik/config.py
# class StatikConfig(YamlLoadable):
#     def __init__(self, *args, **kwargs):
#     def __repr__(self):


# Path: statik/database.py
from io import open
from sqlalchemy import String, Integer, Column, Table, ForeignKey, \
    Boolean, DateTime, Text, create_engine
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.query import Query
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import close_all_sessions
from dateutil.parser import parse as dateutil_parse
from statik.common import ContentLoadable
from statik.fields import *
from statik.errors import *
from statik.utils import *
from statik.config import MarkdownConfig
from statik.pagination import *
from datetime import datetime, date, timedelta, time
from sqlalchemy import func, distinct
import os.path
import yaml
import mlalchemy
import sqlalchemy
import math
import logging

            )

        if isinstance(query, dict):
            logger.debug("Executing query in safe mode (MLAlchemy)")
            return mlalchemy.parse_query(query).to_sqlalchemy(self.session, self.tables).all()
        else:
            logger.debug("Executing unsafe query (Python exec())")
            if additional_locals is not None:
                for k, v in additional_locals.items():
                    locals()[k] = v

            exec(
                compile(
                    'result = %s' % query.strip(),
                    '<string>',
                    'exec'
                ),
                globals(),
                locals()
            )
            return locals()['result']

    def shutdown(self):
        """Shuts down the database engine."""
        close_all_sessions()
        self.engine.dispose()
        # clear all tracked global variables
        clear_tracked_globals()



class StatikDatabaseInstance(ContentLoadable):