<commit_before>import os
os.environ["NLS_LANG"] = "AMERICAN_AMERICA.UTF8"

from types import NoneType
from datetime import date, datetime
from decimal import Decimal

import cx_Oracle

from pony import orm, dbschema, sqlbuilding, dbapiprovider, sqltranslation
from pony.dbapiprovider import DBAPIProvider, wrap_dbapi_exceptions, LongStr, LongUnicode
from pony.utils import is_utf8, throw

def get_provider(*args, **keyargs):
    return OraProvider(*args, **keyargs)

trigger_template = """
create trigger %s
  before insert on %s  
  for each row
begin
  if :new.%s is null then
    select %s.nextval into :new.%s from dual;
  end if;
end;"""

class OraTable(dbschema.Table):
    def create(table, provider, connection, created_tables=None):
        commands = table.get_create_commands(created_tables)
        for i, sql in enumerate(commands):
            if orm.debug:
                print sql
                print
            cursor = connection.cursor()
            try: provider.execute(cursor, sql)
            except orm.DatabaseError, e:
                if e.exceptions[0].args[0].code == 955:
                    if orm.debug: print 'ALREADY EXISTS:', e.args[0].message
                    if not i:
                        if len(commands) > 1: print 'SKIP FURTHER DDL COMMANDS FOR TABLE %s\n' % table.name
                        return
                else: raise
    def get_create_commands(table, created_tables=None):
        result = dbschema.Table.get_create_commands(table, created_tables, False)
        for column in table.column_list:
            if column.is_pk == 'auto':
                quote_name = table.schema.provider.quote_name
                case = table.schema.case
                seq_name = quote_name(table.name + '_SEQ')
                result.append(case('create sequence %s nocache') % seq_name)
                table_name = quote_name(table.name)
                trigger_name = quote_name(table.name + '_BI')  # Before Insert
                column_name = quote_name(column.name)
                result.append(case(trigger_template) % (trigger_name, table_name, column_name, seq_name, column_name))
                break
        return result

class OraColumn(dbschema.Column):
    auto_template = None
    
class OraSchema(dbschema.DBSchema):
    table_class = OraTable
    column_class = OraColumn

class OraNoneMonad(sqltranslation.NoneMonad):
    def __init__(monad, translator, value=None):
        assert value in (None, '')
        sqltranslation.ConstMonad.__init__(monad, translator, None)

class OraTranslator(sqltranslation.SQLTranslator):
    dialect = 'Oracle'
    NoneMonad = OraNoneMonad
    
    @classmethod
    def get_normalized_type_of(translator, value):
        if value == '': return NoneType
        return sqltranslation.SQLTranslator.get_normalized_type_of(value)
        
class OraBuilder(sqlbuilding.SQLBuilder):
    dialect = 'Oracle'
    def INSERT(builder, table_name, columns, values, returning=None):
        result = sqlbuilding.SQLBuilder.INSERT(builder, table_name, columns, values)
        if returning is not None:
            result.extend((' RETURNING ', builder.quote_name(returning), ' INTO :new_id'))
        return result
    def SELECT(builder, *sections):
        last_section = sections[-1]
        limit = offset = None
        if last_section[0] == 'LIMIT':
            limit = last_section[1]
            if len(last_section) > 2: offset = last_section[2]
            sections = sections[:-1]
        result = builder.subquery(*sections)
        indent = builder.indent_spaces * builder.indent
        if not limit: pass
        elif not offset:
            result = [ 'SELECT * FROM (\n' ]
            builder.indent += 1
            result.extend(builder.subquery(*sections))
            builder.indent -= 1
            result.extend((indent, ') WHERE ROWNUM <= ', builder(limit)))
        else:
            indent2 = indent + builder.indent_spaces
            result = [ 'SELECT * FROM (\n', indent2, 'SELECT t.*, ROWNUM "row-num" FROM (\n' ]
            builder.indent += 2
            result.extend(builder.subquery(*sections))
            builder.indent -= 2
            result.extend((indent2, ') t '))
            if limit[0] == 'VALUE' and offset[0] == 'VALUE' \
                    and isinstance(limit[1], int) and isinstance(offset[1], int):
                total_limit = [ 'VALUE', limit[1] + offset[1] ]
                result.extend(('WHERE ROWNUM <= ', builder(total_limit), '\n'))
            else: result.extend(('WHERE ROWNUM <= ', builder(limit), ' + ', builder(offset), '\n'))
            result.extend((indent, ') WHERE "row-num" > ', builder(offset)))
        if builder.indent: return '(\n', result, ')'
        return result
    def LIMIT(builder, limit, offset=None):
        assert False
        if not offset: return 'LIMIT ', builder(limit), '\n'
        else: return 'LIMIT ', builder(limit), ' OFFSET ', builder(offset), '\n'

class OraBoolConverter(dbapiprovider.BoolConverter):
    def sql2py(converter, val):
        return bool(val)  # TODO: True/False, T/F, Y/N, Yes/No, etc.
    def sql_type(converter):
        return "NUMBER(1)"

def _string_sql_type(converter):
    if converter.max_len:<commit_msg>Oracle subselect indent fixed<commit_after>import os
os.environ["NLS_LANG"] = "AMERICAN_AMERICA.UTF8"

from types import NoneType
from datetime import date, datetime
from decimal import Decimal

import cx_Oracle

from pony import orm, dbschema, sqlbuilding, dbapiprovider, sqltranslation
from pony.dbapiprovider import DBAPIProvider, wrap_dbapi_exceptions, LongStr, LongUnicode
from pony.utils import is_utf8, throw

def get_provider(*args, **keyargs):
    return OraProvider(*args, **keyargs)

trigger_template = """
create trigger %s
  before insert on %s  
  for each row
begin
  if :new.%s is null then
    select %s.nextval into :new.%s from dual;
  end if;
end;"""

class OraTable(dbschema.Table):
    def create(table, provider, connection, created_tables=None):
        commands = table.get_create_commands(created_tables)
        for i, sql in enumerate(commands):
            if orm.debug:
                print sql
                print
            cursor = connection.cursor()
            try: provider.execute(cursor, sql)
            except orm.DatabaseError, e:
                if e.exceptions[0].args[0].code == 955:
                    if orm.debug: print 'ALREADY EXISTS:', e.args[0].message
                    if not i:
                        if len(commands) > 1: print 'SKIP FURTHER DDL COMMANDS FOR TABLE %s\n' % table.name
                        return
                else: raise
    def get_create_commands(table, created_tables=None):
        result = dbschema.Table.get_create_commands(table, created_tables, False)
        for column in table.column_list:
            if column.is_pk == 'auto':
                quote_name = table.schema.provider.quote_name
                case = table.schema.case
                seq_name = quote_name(table.name + '_SEQ')
                result.append(case('create sequence %s nocache') % seq_name)
                table_name = quote_name(table.name)
                trigger_name = quote_name(table.name + '_BI')  # Before Insert
                column_name = quote_name(column.name)
                result.append(case(trigger_template) % (trigger_name, table_name, column_name, seq_name, column_name))
                break
        return result

class OraColumn(dbschema.Column):
    auto_template = None
    
class OraSchema(dbschema.DBSchema):
    table_class = OraTable
    column_class = OraColumn

class OraNoneMonad(sqltranslation.NoneMonad):
    def __init__(monad, translator, value=None):
        assert value in (None, '')
        sqltranslation.ConstMonad.__init__(monad, translator, None)

class OraTranslator(sqltranslation.SQLTranslator):
    dialect = 'Oracle'
    NoneMonad = OraNoneMonad
    
    @classmethod
    def get_normalized_type_of(translator, value):
        if value == '': return NoneType
        return sqltranslation.SQLTranslator.get_normalized_type_of(value)
        
class OraBuilder(sqlbuilding.SQLBuilder):
    dialect = 'Oracle'
    def INSERT(builder, table_name, columns, values, returning=None):
        result = sqlbuilding.SQLBuilder.INSERT(builder, table_name, columns, values)
        if returning is not None:
            result.extend((' RETURNING ', builder.quote_name(returning), ' INTO :new_id'))
        return result
    def SELECT(builder, *sections):
        last_section = sections[-1]
        limit = offset = None
        if last_section[0] == 'LIMIT':
            limit = last_section[1]
            if len(last_section) > 2: offset = last_section[2]
            sections = sections[:-1]
        result = builder.subquery(*sections)
        indent = builder.indent_spaces * builder.indent
        if not limit: pass
        elif not offset:
            result = [ 'SELECT * FROM (\n' ]
            builder.indent += 1
            result.extend(builder.subquery(*sections))
            builder.indent -= 1
            result.extend((indent, ') WHERE ROWNUM <= ', builder(limit)))
        else:
            indent2 = indent + builder.indent_spaces
            result = [ 'SELECT * FROM (\n', indent2, 'SELECT t.*, ROWNUM "row-num" FROM (\n' ]
            builder.indent += 2
            result.extend(builder.subquery(*sections))
            builder.indent -= 2
            result.extend((indent2, ') t '))
            if limit[0] == 'VALUE' and offset[0] == 'VALUE' \
                    and isinstance(limit[1], int) and isinstance(offset[1], int):
                total_limit = [ 'VALUE', limit[1] + offset[1] ]
                result.extend(('WHERE ROWNUM <= ', builder(total_limit), '\n'))
            else: result.extend(('WHERE ROWNUM <= ', builder(limit), ' + ', builder(offset), '\n'))
            result.extend((indent, ') WHERE "row-num" > ', builder(offset)))
        if builder.indent:
            indent = builder.indent_spaces * builder.indent
            return '(\n', result, indent + ')'
        return result
    def LIMIT(builder, limit, offset=None):
        assert False
        if not offset: return 'LIMIT ', builder(limit), '\n'
        else: return 'LIMIT ', builder(limit), ' OFFSET ', builder(offset), '\n'

class OraBoolConverter(dbapiprovider.BoolConverter):
    def sql2py(converter, val):
        return bool(val)  # TODO: True/False, T/F, Y/N, Yes/No, etc.
    def sql_type(converter):
        return "NUMBER(1)"

def _string_sql_type(converter):
    if converter.max_len:
{'fraction_non_alphanumeric': 0.10976418221422483, 'fraction_numerical': 0.00568235628373899, 'mean_word_length': 2.447600391772772, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3190000', 'n_tokens_mistral': 3116, 'n_tokens_neox': 3018, 'n_words': 766}