当前位置: 首页>>代码示例>>Python>>正文


Python DBSESSION.merge方法代码示例

本文整理汇总了Python中autonomie_base.models.base.DBSESSION.merge方法的典型用法代码示例。如果您正苦于以下问题:Python DBSESSION.merge方法的具体用法?Python DBSESSION.merge怎么用?Python DBSESSION.merge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在autonomie_base.models.base.DBSESSION的用法示例。


在下文中一共展示了DBSESSION.merge方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    op.add_column('payment', sa.Column('created_at', sa.DateTime()))
    op.add_column('payment', sa.Column('updated_at', sa.DateTime()))
    op.add_column('payment', sa.Column('bank_id', sa.Integer(), nullable=True))
    op.add_column('payment', sa.Column('exported', sa.Boolean(), default=False))
    op.add_column('payment', sa.Column(
        'tva_id',
        sa.Integer(),
        sa.ForeignKey('tva.id'),
        nullable=True,
    ))
    op.add_column(
        'payment',
        sa.Column('remittance_amount', sa.Integer(), nullable=True)
    )
    op.add_column(
        'tva',
        sa.Column('compte_a_payer', sa.String(125), default='')
    )
    from autonomie_base.models.base import DBSESSION
    from autonomie.models.task import Payment

    session = DBSESSION()

    for payment in Payment.query():
        payment.remittance_amount = payment.amount
        payment.exported = True
        payment.created_at = payment.updated_at = payment.date
        session.merge(payment)
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:31,代码来源:3_1_ajout_bank_id_to_payments_59f05bb3051d.py

示例2: migrate_datas

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def migrate_datas():
    logger = logging.getLogger("alembic.autonomie")
    from autonomie_base.models.base import DBSESSION
    session = DBSESSION()
    from autonomie.models.config import Config
    import json

    from autonomie.models.files import (
        File,
        FileType,
    )
    json_str = Config.get_value("attached_filetypes", "[]")
    try:
        configured_filetypes = json.loads(json_str)
    except:
        logger.exception(u"Error in json str : %s" % json_str)
        configured_filetypes = []
    if configured_filetypes:
        result = []
        for filetype_label in configured_filetypes:
            if filetype_label:
                filetype = FileType(label=filetype_label)
                session.add(filetype)
                session.flush()
                result.append(filetype)

        for typ_ in result:
            query = File.query().filter_by(label=typ_.label)
            for file_ in query:
                file_.file_type_id = typ_.id
                session.merge(file_)
        session.flush()
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:34,代码来源:4_2_0_add_filetype_table_11a62732db65.py

示例3: migrate_datas

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    session = DBSESSION()
    from autonomie.models.accounting.operations import AccountingOperationUpload
    for entry in AccountingOperationUpload.query():
        entry.filetype = "analytical_balance"
        session.merge(entry)
        session.flush()
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:10,代码来源:4_1_compte_de_resultats_13a25f46e412.py

示例4: migrate_datas

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    session = DBSESSION()
    from alembic.context import get_bind
    connection = get_bind()

    from autonomie.models.user.login import Login
    op.execute("update groups set editable=0;")
    op.execute("update groups set `primary`=0;")
    op.execute(
        "update groups set `primary`=1 where name IN ('admin', 'contractor', 'manager')"
    )
    op.execute('update accounts set civilite="Monsieur"')

    for user in connection.execute(user_helper.select()):
        login = Login(
            user_id=user.id,
            login=user.login,
        )
        login.pwd_hash = user.password,
        login.active = user.active == 'Y'
        session.add(login)
        session.flush()
        op.execute(
            'UPDATE user_groups set login_id="%s" where user_id=%s' % (
                login.id, user.id
            )
        )
    op.drop_column("accounts", "login")
    op.drop_column("accounts", "password")
    op.drop_column("accounts", "active")


    from autonomie.models.user.user import User
    for userdatas in connection.execute(userdatas_helper.select()):
        if userdatas.user_id is None:
            user = User(
                lastname=userdatas.coordonnees_lastname,
                firstname=userdatas.coordonnees_firstname,
                email=userdatas.coordonnees_email1,
                civilite=userdatas.coordonnees_civilite or 'Monsieur',
            )
            session.add(user)
            session.flush()
            connection.execute(
                userdatas_helper.update().where(
                    userdatas_helper.c.id == userdatas.id
                ).values(user_id=user.id)
            )
        else:
            user = User.get(userdatas.user_id)
            user.civilite = userdatas.coordonnees_civilite or 'Monsieur'
            session.merge(user)
            session.flush()

    op.execute('update accounts set civilite="Monsieur" where civilite is NULL')
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:58,代码来源:4_2_0_migrate_user_table_foreign_keys_1ad4b3e78299.py

示例5: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    from autonomie.models.task import Invoice, CancelInvoice, ManualInvoice
    from autonomie_base.models.base import DBSESSION
    for table in "invoice", "cancelinvoice", "manualinv":
        if not column_exists(table, "financial_year"):
            op.add_column(table, sa.Column("financial_year", sa.Integer,
                                                        nullable=False))
    for type_ in (Invoice, CancelInvoice, ManualInvoice):
        for document in type_.query():
            document.financial_year = document.taskDate.year
            DBSESSION.merge(document)
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:13,代码来源:1_5_migrating_financ_4a4eba558244.py

示例6: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    op.execute(u"Alter table tva modify name VARCHAR(15)")
    op.execute(u"Alter table tva modify active tinyint(1)")
    op.add_column('tva', sa.Column('mention', sa.Text(), default=''))

    from autonomie.models.tva import Tva
    from autonomie_base.models.base import DBSESSION
    session = DBSESSION()
    for tva in session.query(Tva):
        if tva.value <= 0:
            tva.mention = u"TVA non applicable selon l'article 259b du CGI."
            session.merge(tva)
        else:
            tva.mention = u"TVA {0} %".format(tva.value / 100.0)
            session.merge(tva)
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:17,代码来源:3_2_add_mention_to_tva_1cf6d10d40cf.py

示例7: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    from autonomie.models.user import User
    logger = logging.getLogger("alembic.migrate_code_compta")
    op.add_column("company", sa.Column("code_compta", sa.String(30), default=0))
    dbsession = DBSESSION()
    for user in User.query():
        code_compta = user.code_compta
        companies = user.companies
        if code_compta not in [u"0", None, u""]:
            if len(companies) == 1:
                company = companies[0]
                company.code_compta = code_compta
                dbsession.merge(company)
            else:
                logger.warn(u"User {0} has a code_compta and multiple \
companies".format(user.id))
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:18,代码来源:1_6_migrate_code_com_29299007fe7d.py

示例8: assign_number

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
    def assign_number(cls, invoice, template):
        """
        This function should be run within an SQL transaction to enforce
        sequence index unicity.
        """
        if invoice.official_number:
            raise ValueError('This invoice already have an official number')

        db = DBSESSION()
        formatter = InvoiceNumberFormatter(invoice, cls.SEQUENCES_MAP)
        invoice_number = formatter.format(template)

        involved_sequences = cls.get_involved_sequences(invoice, template)

        with db.begin_nested():
            # Create SequenceNumber objects (the index useages have not been
            # booked until now).
            for sequence, next_index in involved_sequences:
                sn = SequenceNumber(
                    sequence=sequence.db_key,
                    index=next_index,
                    task_id=invoice.id,
                )
                db.add(sn)
            invoice.official_number = invoice_number
            db.merge(invoice)

            # Imported here to avoid circular dependencies
            from autonomie.models.task import Task, Invoice, CancelInvoice

            query = Task.query().with_polymorphic([Invoice, CancelInvoice])
            query = query.filter(
                Task.official_number == invoice_number,
                Task.id != invoice.id,
                Task.legacy_number == False,
            ).scalar()

            if query is not None:
                # This case is exceptionnal, we can afford a crash here
                # Context manager will take care of rolling back
                # subtransaction.
                raise ValueError(
                    'Invoice number collision, rolling back to avoid it'
                )

        return invoice_number
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:48,代码来源:invoice_sequence_number.py

示例9: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    from autonomie.models.company import Company
    from autonomie.models.files import File
    from autonomie_base.models.base import DBSESSION
    from alembic.context import get_bind
    from autonomie.models.config import ConfigFiles

    for i in ('header_id', 'logo_id',):
        col = sa.Column(i, sa.Integer, sa.ForeignKey('file.id'))
        op.add_column('company', col)

    query = "select id, header, logo from company;"
    conn = get_bind()
    result = conn.execute(query)

    session = DBSESSION()

    for id_, header, logo in result:
        company = Company.get(id_)
        basepath = u"%scompany/%s" % (BASEFILEPATH, id_,)

        if header:
            header_path = u"%s/header/%s" % (basepath, header)
            try:
                file_datas = load_file_struct(header_path, header)
            except:
                print("Error while loading a header")
                print(id_)
                file_datas = None
            if file_datas:
                company.header = file_datas
                session.add(company.header_file)
                session.flush()

        if logo:
            logo_path = u"%s/logo/%s" % (basepath, logo)
            try:
                file_datas = load_file_struct(logo_path, logo)
            except:
                print("Error while loading a logo")
                print(id_)
                file_datas = None
            if file_datas:
                company.logo = file_datas
                company = session.merge(company)
                session.flush()

    filepath = u"%s/main/logo.png" % BASEFILEPATH
    if os.path.isfile(filepath):
        ConfigFiles.set('logo.png', load_file_struct(filepath, 'logo.png'))

    filepath = u"%s/main/accompagnement_header.png" % BASEFILEPATH
    if os.path.isfile(filepath):
        ConfigFiles.set(
            'accompagnement_header.png',
            load_file_struct(filepath, 'accompagnement_header.png')
        )
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:59,代码来源:2_3_1_2_3_1_header_and_logo_in_db_40c1f95213d0.py

示例10: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    from autonomie.models.client import Client
    for table in ("estimation", "invoice", "cancelinvoice"):
        op.add_column(table, sa.Column("address", sa.Text, default=""))
        op.add_column(table,
                sa.Column("client_id",
                          sa.Integer,
                          sa.ForeignKey("customer.id")))

    for obj in (Invoice, CancelInvoice, Estimation):
        for doc in obj.query():
            if doc.project is not None and doc.project.client_id is not None:
                client = Client.get(doc.project.client_id)
                if client is not None:
                    doc.address = client.full_address
                    doc.client_id = client.id
            if len(doc._number) > 10:
                doc._number = doc._number[10:]
            DBSESSION.merge(doc)
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:21,代码来源:1_5_address_field_on_23fd141c9484.py

示例11: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    disable_listeners()
    op.add_column('task', sa.Column('date', sa.Date()))
    from autonomie.models.task import Task
    from autonomie_base.models.base import DBSESSION

    session = DBSESSION()
    for task in Task.query().filter(Task.type_!='manualinvoice'):
        task.date = task.taskDate
        session.merge(task)
    session.flush()

    op.execute("alter table groups modify label VARCHAR(255);")
    op.execute("alter table payment modify remittance_amount VARCHAR(255);")
    from autonomie.models.user import User, Group
    for group_id, group_name, group_label in GROUPS:
        group = session.query(Group).filter(Group.name==group_name).first()
        if group is None:
            group = Group(name=group_name, label=group_label)
            session.add(group)
            session.flush()

        users = session.query(User).filter(User.primary_group==group_id)
        for user in users:
            user._groups.append(group)
            session.merge(user)

    label = u"Peut saisir/modifier/supprimer les paiements de ses factures"
    group_name = "payment_admin"
    group = Group.query().filter(Group.name==group_name).first()
    if group is not None:
        group.label = label
        session.merge(group)
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:35,代码来源:3_2_add_base_groups_58df01afdaad.py

示例12: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
def upgrade():
    from autonomie.models.task import (
        TaskLine,
        TaskLineGroup,
        Task,
        Estimation,
        CancelInvoice,
        Invoice,
    )
    from autonomie_base.models.base import (
        DBSESSION,
    )

    session = DBSESSION()

    index = 0
    query = Task.query()
    query = query.with_polymorphic([Invoice, CancelInvoice, Estimation])
    query = query.filter(
        Task.type_.in_(['invoice', 'estimation', 'cancelinvoice'])
    )
    for task in query:
        try:
            task_lines = task.default_line_group.lines
        except:
            continue
        for index, line in enumerate(task.lines):
            try:
                task_line = task_lines[index]
                task_line.unity = line.unity
                session.merge(task_line)

            except:
                pass

        index += 1
        if index % 100 == 0:
            session.flush()
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:40,代码来源:3_0_fix_missing_unities_54de05a93319.py

示例13: Anonymizer

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]
class Anonymizer(object):
    def __init__(self, logger):
        self.us_faker = Faker()
        self.faker = Faker('fr_FR')
        self.logger = logger
        self.session = DBSESSION()

    def _zipcode(self):
        if hasattr(self.faker, 'zipcode'):
            return self.faker.zipcode()
        else:
            return self.faker.postcode()

    def _an_activity(self):
        from autonomie.models.activity import Activity, ActivityType
        from autonomie.models.workshop import Workshop

        for activity in self.session.query(Activity):
            for fieldname in (
                'point',
                'objectifs',
                'action',
                'documents',
                'notes'
            ):
                setattr(activity, fieldname, self.faker.text())

        for workshop in self.session.query(Workshop).options(load_only('id')):
            workshop.description = self.faker.text()
            self.session.merge(workshop)

        type_labels = (
            u"RV conseil",
            u"RV suivi",
            u"RV Gestion",
            u"RV Admin",
            u"RV RH",
            u"RV Compta",
            u"RV hebdo",
            u"RV Mensuel",
        )

        for index, typ in enumerate(self.session.query(ActivityType).all()):
            typ.label = type_labels[index % 7]

    def _an_commercial(self):
        from autonomie.models.commercial import TurnoverProjection
        for t in self.session.query(TurnoverProjection):
            t.comment = self.faker.text()

    def _an_company(self):
        from autonomie.models.company import Company
        for comp in self.session.query(Company):
            comp.name = self.faker.company()
            comp.goal = self.faker.bs()
            comp.comments = self.faker.catch_phrase()
            comp.phone = self.faker.phone_number()
            comp.mobile = self.faker.phone_number()
            comp.email = self.faker.ascii_safe_email()
            header = build_header(
                u"{0}\n {1} - {2}".format(comp.name, comp.phone, comp.email)
            )
            comp.header = {'name': 'header.png', 'data': header}
        self.session.execute(u"update company set cgv=''")

    def _an_competence(self):
        from autonomie.models.competence import (
            CompetenceGridItem,
            CompetenceGridSubItem,
        )
        for item in self.session.query(CompetenceGridItem):
            item.progress = self.faker.text()
        for item in self.session.query(CompetenceGridSubItem):
            item.comments = self.faker.text()

    def _an_config(self):
        from autonomie.models.config import Config, ConfigFiles

        Config.set('cae_admin_mail', self.faker.ascii_safe_email())
        Config.set('welcome', self.faker.sentence(nb_words=15))
        ConfigFiles.set(
            'logo.png',
            {
                'data': pkg_resources.resource_stream(
                    'autonomie',
                    'static/img/autonomie.jpg'
                ),
                'filename': 'logo.jpg',
            }
        )
        Config.set('coop_cgv', self.faker.paragraph(nb_sentences=40))
        Config.set('coop_pdffootertitle', u"""Une activité de ma CAE SARL SCOP à \
capital variable""")
        Config.set('coop_pdffootercourse', u"""Organisme de formation N° de déclaration \
d'activité au titre de la FPC : xx xx xxxxx. MA CAE est exonérée de TVA pour \
les activités s'inscrivant dans le cadre de la formation professionnelle \
conformément à l'art. L920-4 du Code du travail et de l'art. 202 C de \
l'annexe II du code général des impôts""")
        footer = u"""RCS XXXX 000 000 000 00000 - SIRET 000 \
000 000 000 00 - Code naf 0000Z TVA INTRACOM : FR0000000. Siège social : 10 \
#.........这里部分代码省略.........
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:103,代码来源:anonymize.py

示例14: upgrade

# 需要导入模块: from autonomie_base.models.base import DBSESSION [as 别名]
# 或者: from autonomie_base.models.base.DBSESSION import merge [as 别名]

#.........这里部分代码省略.........

    from autonomie.models.task import (
        Invoice,
        CancelInvoice,
        Estimation,
    )
    # Migration des customer_id et project_id au niveau de la table Task
    index = 0

    for type_ in "invoice", "cancelinvoice", "estimation":
        conditions = "paymentConditions"
        if type_ == "cancelinvoice":
            conditions = "reimbursementConditions"

        request = "select id, customer_id, project_id, number, \
sequenceNumber, displayedUnits, expenses, expenses_ht, address, %s \
from %s;" % (conditions, type_)
        result = conn.execute(request)

        for index, (id, c_id, p_id, number, seq_number, display, expenses,
                    expenses_ht, address, conditions) in enumerate(result):

            request = sa.text(u"update task set \
project_id=:p_id, \
customer_id=:c_id, \
_number=:number, \
sequence_number=:seq_number, \
display_units=:display, \
expenses=:expenses, \
expenses_ht=:expenses_ht, \
address=:address, \
payment_conditions=:conditions \
where id=:id;"
                             )

            conn.execute(
                request,
                p_id=p_id,
                c_id=c_id,
                number=number,
                seq_number=seq_number,
                display=display,
                expenses=expenses,
                expenses_ht=expenses_ht,
                address=address,
                conditions=conditions,
                id=id,
            )
            if index % 50 == 0:
                session.flush()

    for type_ in ('invoice', 'cancelinvoice'):
        request = "select id, officialNumber from %s" % (type_,)
        result = conn.execute(request)

        for index, (id, official_number) in enumerate(result):
            request = sa.text(u"update task set \
official_number=:official_number \
where id=:id;"
                             )
            conn.execute(
                request,
                official_number=official_number,
                id=id,
            )
            if index % 50 == 0:
                session.flush()

    for factory in (Invoice, CancelInvoice, Estimation,):
        for document in factory.query().options(undefer_group('edit')):
            document.ttc = document.total()
            document.ht = document.total_ht()
            document.tva = document.tva_amount()
            session.merge(document)
            index += 1
        if index % 50 == 0:
            session.flush()

    # Drop old constraints
    for table in ('estimation', 'invoice', 'cancelinvoice'):
        for num in [2,3,4]:
            key = "%s_ibfk_%s" % (table, num,)
            cmd = "ALTER TABLE %s DROP FOREIGN KEY %s;" % (table, key)
            try:
                print(cmd)
                conn.execute(cmd)
            except:
                print("Error while droping a foreignkey : %s %s" % (table, key))

        for column in ('customer_id', 'project_id', 'number', \
                       'sequenceNumber', 'displayedUnits', 'expenses', \
                       'expenses_ht', 'address'):
            op.drop_column(table, column)

    op.drop_column('cancelinvoice', 'reimbursementConditions')
    op.drop_column('estimation', 'paymentConditions')
    op.drop_column('invoice', 'paymentConditions')

    for table in ('invoice', 'cancelinvoice'):
        op.drop_column(table, 'officialNumber')
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:104,代码来源:2_7_migrate_table_datas_428f9d451e18.py


注:本文中的autonomie_base.models.base.DBSESSION.merge方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。