Returns the SQL to create a new foreign key.

        :rtype: sql
333432
def get_create_foreign_key_sql(self, foreign_key, table):
        
        if isinstance(table, Table):
            table = table.get_quoted_name(self)

        query = "ALTER TABLE %s ADD %s" % (
            table,
            self.get_foreign_key_declaration_sql(foreign_key),
        )

        return query
780085
def get_sql(self):
        
        alias = self.get_alias()
        if alias:
            return '{0} AS {1}'.format(self.get_from_name(), alias)

        return self.get_identifier()
964996
def create(self, **kwargs):
        
        obj = self.resource(**kwargs)
        obj.save(force_insert=True)
        return obj
1035753
def create_database(self):
        
        if not self._database_exists():
            con = psycopg2.connect(host=self.host, database="postgres",
                user=self.user, password=self.password, port=self.port)
            con.set_isolation_level(
                psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
            query = "CREATE DATABASE {0};".format(self.dbname)
            c = con.cursor()
            c.execute(query)            
            con.close()


            if self.normalize:
                self.open_database()
                query = "CREATE EXTENSION IF NOT EXISTS \"plperlu\";"
                self.execute_sql(query)
    #            query = """CREATE OR REPLACE FUNCTION normalize(str text)
    #RETURNS text
    #AS $$
    #import unicodedata
    #return ''.join(c for c in unicodedata.normalize('NFKD', str)
    #if unicodedata.category(c) != 'Mn')
    #$$ LANGUAGE plpython3u IMMUTABLE;"""
    #             query = """CREATE OR REPLACE FUNCTION normalize(mystr text)
    #   RETURNS text
    # AS $$
    #     from unidecode import unidecode
    #     return unidecode(mystr.decode("utf-8"))
    # $$ LANGUAGE plpythonu IMMUTABLE;"""
                query = """CREATE OR REPLACE FUNCTION normalize(text)
      RETURNS text
    AS $$
        use Text::Unidecode;
        return unidecode(shift);
    $$ LANGUAGE plperlu IMMUTABLE;"""
                self.execute_sql(query)
                self.commit()
                self.close_database()
598545
def formfield_for_foreignkey(self, db_field, *args, **kwargs):
        
        formfield = super(FluentLayoutsMixin, self).formfield_for_foreignkey(
            db_field, *args, **kwargs)
        if db_field.name == 'layout':
            formfield.queryset = formfield.queryset.for_model(self.model)
        return formfield
160900
def create_table(self, model):
        
        self.orm[model._meta.table_name] = model
        model._meta.database = self.database
        self.ops.append(model.create_table)
        return model
939801
def first_or_new(self, _attributes=None, **attributes):
        
        if _attributes is not None:
            attributes.update(_attributes)

        instance = self.where(attributes).first()

        if instance is None:
            instance = self._related.new_instance()
            instance.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        return instance
464388
def foreign_keys(self):
        
        foreign_keys = self.__current_descriptor.get('foreignKeys', [])
        for key in foreign_keys:
            key.setdefault('fields', [])
            key.setdefault('reference', {})
            key['reference'].setdefault('resource', '')
            key['reference'].setdefault('fields', [])
            if not isinstance(key['fields'], list):
                key['fields'] = [key['fields']]
            if not isinstance(key['reference']['fields'], list):
                key['reference']['fields'] = [key['reference']['fields']]
        return foreign_keys
1193276
def _model_foreign(ins):
    
    fks = []
    for t in ins.tables:
        fks.extend([
            SaForeignkeyDoc(
                key=fk.column.key,
                target=fk.target_fullname,
                onupdate=fk.onupdate,
                ondelete=fk.ondelete
            )
            for fk in t.foreign_keys])
    return fks
944704
def sql(self, query):
        
        # Get the schema by adding a LIMIT 0 on to the end of the query. If
        # there is already a limit in the query, we find and remove it
        limited_query = 'SELECT * FROM ({}) t0 LIMIT 0'.format(query)
        schema = self._get_schema_using_query(limited_query)
        return ops.SQLQueryResult(query, schema, self).to_expr()
1332577
def sql(self, dialect=None, inserts=False, creates=True,
            drops=True, metadata_source=None):
        
        result = [self.ddl(dialect, creates=creates, drops=drops)]
        if inserts:
            for row in self.inserts(dialect):
                result.append(row)
        return '\n'.join(result)
1119233
def as_sql(self):
        

        labels, data = self._get_table()
        table = SqlTable(labels, data, "{:.3f}", "\n")
        return str(table)
76319
def _select_sql(self, **kwargs):
        
        return 'SELECT {distinct}{modifier}{select}'.format(
              distinct='DISTINCT ' if self._distinct else '',
              modifier='{} '.format(' '.join(self._modifiers)) if self._modifiers else '',
              select=','.join(term.get_sql(with_alias=True, subquery=True, **kwargs)
                              for term in self._selects),
        )
123323
def _set_join(self, query=None):
        
        if not query:
            query = self._query

        foreign_key = '%s.%s' % (self._related.get_table(), self._second_key)

        query.join(self._parent.get_table(), self.get_qualified_parent_key_name(), '=', foreign_key)
376556
def _columns_sql(self, with_namespace=False, **kwargs):
        
        return ' ({columns})'.format(
              columns=','.join(term.get_sql(with_namespace=False, **kwargs)
                               for term in self._columns)
        )
1038605
def to_sql(cls, qc, **kwargs):
        
        # we first insert an empty DF in order to create the full table in the database
        # This also helps to validate the input against pandas
        # we would like to_sql() to complete only when all rows have been inserted into the database
        # since the mapping operation is non-blocking, each partition will return an empty DF
        # so at the end, the blocking operation will be this empty DF to_pandas

        empty_df = qc.head(1).to_pandas().head(0)
        empty_df.to_sql(**kwargs)
        # so each partition will append its respective DF
        kwargs["if_exists"] = "append"
        columns = qc.columns

        def func(df, **kwargs):
            df.columns = columns
            df.to_sql(**kwargs)
            return pandas.DataFrame()

        map_func = qc._prepare_method(func, **kwargs)
        result = qc._map_across_full_axis(1, map_func)
        # blocking operation
        result.to_pandas()
1233805
def get_table(self, table_name, primary_id=None, primary_type=None):
        
        return self.create_table(table_name, primary_id, primary_type)