def db_default(self, column_name, value): cursor = Transaction().connection.cursor() cursor.execute('ALTER TABLE `%s` ' 'MODIFY COLUMN `%s` %s' % (self.table_name, column_name, self._column_definition(column_name, default=value))) self._update_definitions(columns=True)
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor super(ProductMedia, cls).__register__(module_name) media_table = cls.__table__() if TableHandler.table_exist(cursor, 'product_product_imageset'): # Migrate data from ProductImageSet table to ProductMedia table imageset_table = Table('product_product_imageset') cursor.execute(*media_table.insert( columns=[ media_table.sequence, media_table.product, media_table.template, media_table.static_file, ], values=imageset_table.select( Literal(10), imageset_table.product, imageset_table.template, imageset_table.image ) )) TableHandler.drop_table( cursor, 'product.product.imageset', 'product_product_imageset', cascade=True )
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor sql_table = cls.__table__() table = TableHandler(cursor, cls, module_name) if not table.column_exist('shop'): table.add_raw_column( 'shop', cls.shop.sql_type(), cls.shop.sql_format, None, None ) else: Shop = Pool().get('sale.shop') shops = Shop.search([]) if shops: sales = cls.search([ ('shop', '=', None), ]) for sale in sales: cursor.execute(*sql_table.update( columns=[sql_table.shop], values=[shops[0].id], where=sql_table.id == sale.id)) else: logging.getLogger('sale shop').warning( 'You must to create a shop and update module ' 'to assign current sales to new shop.') super(Sale, cls).__register__(module_name)
def add_fk(self, column_name, reference, on_delete=None): if on_delete is not None: on_delete = on_delete.upper() else: on_delete = 'SET NULL' cursor = Transaction().connection.cursor() name = self.table_name + '_' + column_name + '_fkey' name = truncate_constraint_name(name) cursor.execute('SELECT 1 ' 'FROM information_schema.key_column_usage ' 'WHERE table_name = %s AND table_schema = %s ' 'AND constraint_name = %s', (self.table_name, self.table_schema, name)) add = False if not cursor.rowcount: add = True elif self._fk_deltypes.get(column_name) != on_delete: self.drop_fk(column_name) add = True if add: cursor.execute('ALTER TABLE "' + self.table_name + '" ' 'ADD CONSTRAINT "' + name + '" ' 'FOREIGN KEY ("' + column_name + '") ' 'REFERENCES "' + reference + '" ' 'ON DELETE ' + on_delete) self._update_definitions(constraints=True)
def get_creationdate(cls, uri, cache=None): Party = Pool().get('party.party') party = Party.__table__() party_id = cls.vcard(uri) cursor = Transaction().cursor if party_id is None: raise DAV_NotFound if party_id: if cache is not None: cache.setdefault('_contact', {}) ids = cache['_contact'].keys() if party_id not in ids: ids.append(party_id) elif 'creationdate' in cache['_contact'][party_id]: return cache['_contact'][party_id]['creationdate'] else: ids = [party_id] res = None for sub_ids in grouped_slice(ids): red_sql = reduce_ids(party.id, sub_ids) cursor.execute(*party.select(party.id, Extract('EPOCH', party.create_date), where=red_sql)) for party_id2, date in cursor.fetchall(): if party_id2 == party_id: res = date if cache is not None: cache['_contact'].setdefault(party_id2, {}) cache['_contact'][party_id2]['creationdate'] = date if res is not None: return res return super(Collection, cls).get_creationdate(uri, cache=cache)
def init(self, module_name): cursor = Transaction().cursor # Migration from 1.6: corrected misspelling of ounce (was once) cursor.execute("UPDATE ir_model_data "\ "SET fs_id = REPLACE(fs_id, 'uom_once', 'uom_ounce') "\ "WHERE fs_id = 'uom_once' AND module = 'product'") super(Uom, self).init(module_name)
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') sql_table = cls.__table__() super(PaymentTermLine, cls).__register__(module_name) cursor = Transaction().cursor table = TableHandler(cursor, cls, module_name) # Migration from 1.0 percent change into percentage if table.column_exist('percent'): cursor.execute(*sql_table.update( columns=[sql_table.percentage], values=[sql_table.percent * 100])) table.drop_column('percent', exception=True) # Migration from 2.2 if table.column_exist('delay'): cursor.execute(*sql_table.update( columns=[sql_table.day], values=[31], where=sql_table.delay == 'end_month')) table.drop_column('delay', exception=True) lines = cls.search([]) for line in lines: if line.percentage: cls.write([line], { 'divisor': cls.round(Decimal('100.0') / line.percentage, cls.divisor.digits[1]), }) # Migration from 2.4: drop required on sequence table.not_null_action('sequence', action='remove')
def __register__(cls, module_name): pool = Pool() Sequence = pool.get('account.fiscalyear.invoice_sequence') sequence = Sequence.__table__() sql_table = cls.__table__() super(FiscalYear, cls).__register__(module_name) cursor = Transaction().connection.cursor() table = cls.__table_handler__(module_name) # Migration from 4.2: Use Match pattern for sequences if (table.column_exist('in_invoice_sequence') and table.column_exist('in_credit_note_sequence') and table.column_exist('out_invoice_sequence') and table.column_exist('out_credit_note_sequence')): cursor.execute(*sequence.insert(columns=[ sequence.sequence, sequence.fiscalyear, sequence.company, sequence.out_invoice_sequence, sequence.out_credit_note_sequence, sequence.in_invoice_sequence, sequence.in_credit_note_sequence], values=sql_table.select( Literal(20), sql_table.id, sql_table.company, sql_table.out_invoice_sequence, sql_table.out_credit_note_sequence, sql_table.in_invoice_sequence, sql_table.in_credit_note_sequence))) table.drop_column('out_invoice_sequence') table.drop_column('out_credit_note_sequence') table.drop_column('in_invoice_sequence') table.drop_column('in_credit_note_sequence')
def __register__(cls, module_name): cursor = Transaction().cursor # Migration from 1.6: corrected misspelling of ounce (was once) cursor.execute("UPDATE ir_model_data " "SET fs_id = REPLACE(fs_id, 'uom_once', 'uom_ounce') " "WHERE fs_id = 'uom_once' AND module = 'product'") super(Uom, cls).__register__(module_name)
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor sql_table = cls.__table__() # Migration from 1.8: new field company table = TableHandler(cursor, cls, module_name) company_exist = table.column_exist('company') super(Statement, cls).__register__(module_name) # Migration from 1.8: fill new field company if not company_exist: offset = 0 limit = cursor.IN_MAX statements = True while statements: statements = cls.search([], offset=offset, limit=limit) offset += limit for statement in statements: cls.write([statement], { 'company': statement.journal.company.id, }) table = TableHandler(cursor, cls, module_name) table.not_null_action('company', action='add') # Migration from 3.2: remove required on start/end balance table.not_null_action('start_balance', action='remove') table.not_null_action('end_balance', action='remove') # Migration from 3.2: add required name cursor.execute(*sql_table.update([sql_table.name], [sql_table.id.cast(cls.name.sql_type().base)], where=sql_table.name == None))
def __register__(cls, module_name): pool = Pool() Party = pool.get('party.party') TableHandler = backend.get('TableHandler') cursor = Transaction().cursor party = Party.__table__() super(PartyIdentifier, cls).__register__(module_name) party_h = TableHandler(cursor, Party, module_name) if (party_h.column_exist('vat_number') and party_h.column_exist('vat_country')): identifiers = [] cursor.execute(*party.select( party.id, party.vat_number, party.vat_country, where=(party.vat_number != Null) | (party.vat_country != Null))) for party_id, number, country in cursor.fetchall(): code = (country or '') + (number or '') if not code: continue type = None if vat.is_valid(code): type = 'eu_vat' identifiers.append( cls(party=party_id, code=code, type=type)) cls.save(identifiers) party_h.drop_column('vat_number') party_h.drop_column('vat_country')
def get_creationdate(cls, uri, cache=None): pool = Pool() object_name, object_id = cls._uri2object(uri, cache=cache) if object_name == 'ir.attachment': Model = pool.get(object_name) if object_id: if cache is not None: cache.setdefault(Model.__name__, {}) ids = cache[Model.__name__].keys() if object_id not in ids: ids.append(object_id) elif 'creationdate' in cache[Model.__name__][object_id]: return cache[Model.__name__][object_id][ 'creationdate'] else: ids = [object_id] res = None cursor = Transaction().cursor for i in range(0, len(ids), cursor.IN_MAX): sub_ids = ids[i:i + cursor.IN_MAX] red_sql, red_ids = reduce_ids('id', sub_ids) cursor.execute('SELECT id, ' 'EXTRACT(epoch FROM create_date) ' 'FROM "' + Model._table + '" ' 'WHERE ' + red_sql, red_ids) for object_id2, date in cursor.fetchall(): if object_id2 == object_id: res = date if cache is not None: cache[Model.__name__].setdefault(object_id2, {}) cache[Model.__name__][object_id2][ 'creationdate'] = date if res is not None: return res return time.time()
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().connection.cursor() pool = Pool() Line = pool.get('account.invoice.payment_term.line') sql_table = cls.__table__() line = Line.__table__() # Migration from 4.0: rename long table old_model_name = 'account.invoice.payment_term.line.relativedelta' old_table = config.get( 'table', old_model_name, default=old_model_name.replace('.', '_')) if TableHandler.table_exist(old_table): TableHandler.table_rename(old_table, cls._table) super(PaymentTermLineRelativeDelta, cls).__register__(module_name) line_table = Line.__table_handler__(module_name) # Migration from 3.4 fields = ['day', 'month', 'weekday', 'months', 'weeks', 'days'] if any(line_table.column_exist(f) for f in fields): columns = ([line.id.as_('line')] + [Column(line, f) for f in fields]) cursor.execute(*sql_table.insert( columns=[sql_table.line] + [Column(sql_table, f) for f in fields], values=line.select(*columns))) for field in fields: line_table.drop_column(field)
def transition_check(self): Plots = Pool().get('forest.plot') Preco = Pool().get('forest_work.preconisation') plots_succeed = [] plots_failed = [] Lignes = Preco.browse(Transaction().context.get('active_ids')) for ligne in Lignes: cursor = Transaction().cursor cursor.execute( 'SELECT p.id ' 'FROM forest_plot p ' 'WHERE p.id=%s ' 'GROUP BY p.id' % (ligne.plot.id)) for plotid in cursor.fetchall(): plots = Plots.browse(plotid) for plot in plots: try: if plot.travaux: print "plots_failed ok" self.create_travaux(plot) plots_failed.append(plot.id) else: print "plots_succeed ok" self.create_travaux(plot) plots_succeed.append(plot.id) except Exception, e: raise self.result.plots_succeed = plots_succeed self.result.plots_failed = plots_failed
def restore_default_party_lang_from_4_2(cls): from trytond.transaction import Transaction from sql import Null, Table, Cast from sql.operators import Concat from trytond.pool import Pool TableHandler = backend.get('TableHandler') if not TableHandler.table_exist('ir_property'): return pool = Pool() property = Table('ir_property') Lang = pool.get('ir.lang') field = pool.get('ir.model.field').__table__() lang = Lang.__table__() cursor = Transaction().connection.cursor() query_table = property.join(lang, condition=( property.value == Concat('ir.lang,', Cast(lang.id, 'VARCHAR')) )).join(field, condition=((property.field == field.id) & (field.name == 'lang'))) cursor.execute( *query_table.select(lang.id, where=property.res == Null)) result = cursor.fetchone() if result: result = list(result) default_lang = Lang(result[0]) print('Default Language restored [%s]' % default_lang.rec_name) pool.get('party.configuration.party_lang' ).create([{'party_lang': default_lang}]) else: print('No default language on party configuration found')
def __register__(cls, module_name): cursor = Transaction().cursor model_data = Table('ir_model_data') # Migration from 3.0: new tax rates if module_name == 'account_nl': for old_id, new_id in ( ('tva_vente_19_6', 'tva_vente_taux_normal'), ('tva_vente_7', 'tva_vente_taux_intermediaire'), ('tva_vente_intracommunautaire_19_6', 'tva_vente_intracommunautaire_taux_normal'), ('tva_vente_intracommunautaire_7', 'tva_vente_intracommunautaire_taux_intermediaire'), ('tva_achat_19_6', 'tva_achat_taux_normal'), ('tva_achat_7', 'tva_achat_taux_intermediaire'), ('tva_achat_intracommunautaire_19_6', 'tva_achat_intracommunautaire_taux_normal'), ): cursor.execute(*model_data.select(model_data.id, where=(model_data.fs_id == new_id) & (model_data.module == module_name))) if cursor.fetchone(): continue cursor.execute(*model_data.update( columns=[model_data.fs_id], values=[new_id], where=(model_data.fs_id == old_id) & (model_data.module == module_name))) super(TaxTemplate, cls).__register__(module_name)
def get_pending_amount(cls, agents, name): pool = Pool() Commission = pool.get('commission') commission = Commission.__table__() cursor = Transaction().connection.cursor() ids = [a.id for a in agents] amounts = dict.fromkeys(ids, None) for sub_ids in grouped_slice(ids): where = reduce_ids(commission.agent, sub_ids) where &= commission.invoice_line == Null query = commission.select(commission.agent, Sum(commission.amount), where=where, group_by=commission.agent) cursor.execute(*query) amounts.update(dict(cursor.fetchall())) digits = cls.pending_amount.digits exp = Decimal(str(10.0 ** -digits[1])) for agent_id, amount in amounts.items(): if amount: # SQLite uses float for SUM if not isinstance(amount, Decimal): amount = Decimal(str(amount)) amounts[agent_id] = amount.quantize(exp) return amounts
def confirmed(cls, registrations): registration_id = registrations[0] Bed = Pool().get("gnuhealth.hospital.bed") cursor = Transaction().cursor bed_id = registration_id.bed.id cursor.execute( "SELECT COUNT(*) \ FROM gnuhealth_inpatient_registration \ WHERE (hospitalization_date::timestamp,discharge_date::timestamp) \ OVERLAPS (timestamp %s, timestamp %s) \ AND (state = %s or state = %s) \ AND bed = CAST(%s AS INTEGER) ", ( registration_id.hospitalization_date, registration_id.discharge_date, "confirmed", "hospitalized", str(bed_id), ), ) res = cursor.fetchone() if registration_id.discharge_date.date() < registration_id.hospitalization_date.date(): cls.raise_user_error( "The Discharge date must later than the \ Admission" ) if res[0] > 0: cls.raise_user_error("bed_is_not_available") else: cls.write(registrations, {"state": "confirmed"}) Bed.write([registration_id.bed], {"state": "reserved"})
def copy_selection_options(): """ Copy the selection field options and create options for the selection field. """ Option = Pool().get('product.attribute.selection_option') cursor = Transaction().cursor cursor.execute( """ SELECT id, selection FROM product_attribute WHERE type_='selection' """ ) # Key value map attribute_kv_map = defaultdict(dict) for row in cursor.fetchall(): id, selection = row for k, v in get_selection_json(selection): option = Option( name=v, attribute=id ) option.save() attribute_kv_map[id][k] = option.id print "Created selection values for %d attributes" % len(attribute_kv_map) return attribute_kv_map
def get_lastmodified(cls, uri, cache=None): pool = Pool() object_name, object_id = cls._uri2object(uri, cache=cache) if object_name == 'ir.attachment': Model = pool.get(object_name) if object_id: if cache is not None: cache.setdefault(Model.__name__, {}) ids = cache[Model.__name__].keys() if object_id not in ids: ids.append(object_id) elif 'lastmodified' in cache[Model.__name__][object_id]: return cache[Model.__name__][object_id][ 'lastmodified'] else: ids = [object_id] res = None cursor = Transaction().cursor table = Model.__table__() for sub_ids in grouped_slice(ids): red_sql = reduce_ids(table.id, sub_ids) cursor.execute(*table.select(table.id, Extract('EPOCH', Coalesce(table.write_date, table.create_date)), where=red_sql)) for object_id2, date in cursor.fetchall(): if object_id2 == object_id: res = date if cache is not None: cache[Model.__name__].setdefault(object_id2, {}) cache[Model.__name__][object_id2][ 'lastmodified'] = date if res is not None: return res return time.time()
def __register__(cls, module_name): TimesheetWork = Pool().get('timesheet.work') cursor = Transaction().cursor table_project_work = TableHandler(cursor, cls, module_name) table_timesheet_work = TableHandler(cursor, TimesheetWork, module_name) migrate_sequence = (not table_project_work.column_exist('sequence') and table_timesheet_work.column_exist('sequence')) super(Work, cls).__register__(module_name) # Migration from 2.0: copy sequence from timesheet to project if migrate_sequence: cursor.execute( 'SELECT t.sequence, t.id ' 'FROM "%s" AS t ' 'JOIN "%s" AS p ON (p.work = t.id)' % ( TimesheetWork._table, cls._table)) for sequence, id_ in cursor.fetchall(): sql = ('UPDATE "%s" ' 'SET sequence = %%s ' 'WHERE work = %%s' % cls._table) cursor.execute(sql, (sequence, id_)) # Migration from 2.4: drop required on sequence table_project_work.not_null_action('sequence', action='remove')
def alter_type(self, column_name, column_type): cursor = Transaction().connection.cursor() cursor.execute('ALTER TABLE `%s` ' 'MODIFY COLUMN `%s` %s' % (self.table_name, column_name, self._column_definition(column_name, typname=column_type))) self._update_definitions(columns=True)
def confirmed(cls, surgeries): surgery_id = surgeries[0] Operating_room = Pool().get('gnuhealth.hospital.or') cursor = Transaction().cursor # Operating Room and end surgery time check if (not surgery_id.operating_room or not surgery_id.surgery_end_date): cls.raise_user_error("Operating Room and estimated end time " "are needed in order to confirm the surgery") or_id = surgery_id.operating_room.id cursor.execute("SELECT COUNT(*) \ FROM gnuhealth_surgery \ WHERE (surgery_date::timestamp,surgery_end_date::timestamp) \ OVERLAPS (timestamp %s, timestamp %s) \ AND (state = %s or state = %s) \ AND operating_room = CAST(%s AS INTEGER) ", (surgery_id.surgery_date, surgery_id.surgery_end_date, 'confirmed', 'in_progress', str(or_id))) res = cursor.fetchone() if (surgery_id.surgery_end_date < surgery_id.surgery_date): cls.raise_user_error("The Surgery end date must later than the \ Start") if res[0] > 0: cls.raise_user_error('or_is_not_available') else: cls.write(surgeries, {'state': 'confirmed'})
def __register__(cls, z_fix__invoice_ar__sale_pos): #super(AfipWSTransaction, cls).__register__(z_fix__invoice_ar__sale_pos) TableHandler = backend.get('TableHandler') cursor = Transaction().cursor table = TableHandler(cursor, cls, z_fix__invoice_ar__sale_pos) cursor.execute("ALTER TABLE account_invoice_ar_afip_transaction\ DROP CONSTRAINT IF EXISTS account_invoice_ar_afip_transaction_invoice_fkey;")
def get_translation_4_nereid(cls, module, ttype, lang, source): "Return translation for source" ttype = unicode(ttype) lang = unicode(lang) source = unicode(source) cache_key = (lang, ttype, source, module) trans = cls._nereid_translation_cache.get(cache_key, -1) if trans != -1: return trans cursor = Transaction().cursor table = cls.__table__() where = ( (table.lang == lang) & (table.type == ttype) & (table.value != '') & (table.value != None) & (table.fuzzy == False) & (table.src == source) ) if module is not None: where &= (table.module == module) cursor.execute(*table.select(table.value, where=where)) res = cursor.fetchone() if res: cls._nereid_translation_cache.set(cache_key, res[0]) return res[0] else: cls._nereid_translation_cache.set(cache_key, False) return None
def count(self): "Return the count of the Items" from trytond.transaction import Transaction # XXX: Ideal case should make a copy of Select query # # https://code.google.com/p/python-sql/issues/detail?id=22 query = self.query query.columns = (Count(Distinct(self.primary_table.id)), ) cursor = Transaction().connection.cursor() # temporarily remove order_by order_by = query.order_by query.order_by = None try: cursor.execute(*query) finally: # XXX: This can be removed when SQL queries can be copied # See comment above query.order_by = order_by res = cursor.fetchone() if res: return res[0] # There can be a case when query return None and then count # will be zero return 0
def ejecutar_nc(self): if self.start.tipoemi=='porid': query = '''SELECT ac.id, ac.number from account_invoice ac left join sigcoop_suministro_suministro ss on ss.id=ac.suministro where ac.state in ('posted') and ac.type = 'out_invoice' and ac.id between \'%s\' and \'%s\' and ss.servicio = \'%s\' order by ac.id ''' % (self.start.desdeid, self.start.hastaid, self.start.servicio.id) elif self.start.consumo_cero: #genero NC para las facturas con cero consumo query = '''SELECT ac.id, ac.number from account_invoice ac left join sigcoop_suministro_suministro ss on ss.id=ac.suministro join sigcoop_consumos_consumo c on c.invoice = ac.id where ac.state in ('posted') and ac.type = 'out_invoice' and c.consumo_neto = 0 and ss.servicio = \'%s\' and ac.periodo = \'%s\' order by ac.id ''' % (self.start.servicio.id, self.start.periodo.id) else: query = '''SELECT ac.id, ac.number from account_invoice ac left join sigcoop_suministro_suministro ss on ss.id=ac.suministro where ac.state in ('posted') and ac.type = 'out_invoice' and ss.servicio = \'%s\' and ss.lista_precios = \'%s\' and ac.periodo = \'%s\' order by ac.id ''' % (self.start.servicio.id, self.start.lista_precios.id, self.start.periodo.id) cursor = Transaction().cursor cursor.execute(query) facturas = cursor.fetchall() self.exito.resumen = "Se van a generar notas de creditos para las siguientes facturas: %s" % map(lambda x: str(x[1]), facturas) return 'exito'
def check_date_overlap(self): cursor = Transaction().cursor if self.state != "done": return True cursor.execute( "SELECT id " "FROM stock_forecast " "WHERE ((from_date <= %s AND to_date >= %s) " "OR (from_date <= %s AND to_date >= %s) " "OR (from_date >= %s AND to_date <= %s)) " "AND warehouse = %s " "AND destination = %s " "AND state = 'done' " "AND company = %s " "AND id != %s", ( self.from_date, self.from_date, self.to_date, self.to_date, self.from_date, self.to_date, self.warehouse.id, self.destination.id, self.company.id, self.id, ), ) forecast_id = cursor.fetchone() if forecast_id: second = self.__class__(forecast_id[0]) self.raise_user_error("date_overlap", {"first": self.rec_name, "second": second.rec_name})
def column_rename(self, old_name, new_name, exception=False): cursor = Transaction().connection.cursor() if self.column_exist(old_name) and not self.column_exist(new_name): temp_table = "_temp_%s" % self.table_name TableHandler.table_rename(self.table_name, temp_table) new_table = TableHandler(self._model, history=self.history) for column, (notnull, hasdef, size, typname) in self._columns.iteritems(): if column == old_name: column = new_name new_table.add_raw_column(column, typname, False, field_size=size) new_columns = new_table._columns.keys() old_columns = [x if x != old_name else new_name for x in new_columns] cursor.execute( ( 'INSERT INTO "%s" (' + ",".join('"%s"' % x for x in new_columns) + ") SELECT " + ",".join('"%s"' % x for x in old_columns) + " " + 'FROM "%s"' ) % (self.table_name, temp_table) ) cursor.execute('DROP TABLE "%s"' % temp_table) self._update_definitions() elif exception and self.column_exist(new_name): raise Exception( "Unable to rename column %s.%s to %s.%s: " "%s.%s already exist!" % (self.table_name, old_name, self.table_name, new_name, self.table_name, new_name) )
def create(self, vals): later = {} vals = vals.copy() cr = Transaction().cursor for field in vals: if field in self._columns\ and hasattr(self._columns[field], 'set'): later[field] = vals[field] for field in later: del vals[field] if vals.get('invoice_ref') == ',': del vals['invoice_ref'] if vals.get('document_ref') == ',': del vals['invoice_ref'] if cr.nextid(self._table): cr.setnextid(self._table, cr.currid(self._table)) new_id = super(DocumentRequest, self).create(vals) request = self.browse(new_id) new_id = request.document.id cr.execute('UPDATE "' + self._table + '" SET id = %s '\ 'WHERE id = %s', (request.document.id, request.id)) ModelStorage.delete(self, request.id) self.write(new_id, later) res = self.browse(new_id) return res.id
def __register__(cls, module_name): pool = Pool() ModelData = pool.get('ir.model.data') TableHandler = backend.get('TableHandler') sql_table = cls.__table__() model_data_sql_table = ModelData.__table__() cursor = Transaction().connection.cursor() # Migration from 3.6: remove double module old_table = 'ir_module_module' if TableHandler.table_exist(old_table): TableHandler.table_rename(old_table, cls._table) super(Module, cls).__register__(module_name) # Migration from 4.0: rename installed to activated cursor.execute(*sql_table.update([sql_table.state], ['activated'], where=sql_table.state == 'installed')) cursor.execute( *sql_table.update([sql_table.state], ['not activated'], where=sql_table.state == 'uninstalled')) # Migration from 4.6: register buttons on ir module button_fs_ids = [ 'module_activate_button', 'module_activate_cancel_button', 'module_deactivate_button', 'module_deactivate_cancel_button', 'module_upgrade_button', 'module_upgrade_cancel_button', ] cursor.execute(*model_data_sql_table.update( [model_data_sql_table.module], ['ir'], where=((model_data_sql_table.module == 'res') & (model_data_sql_table.fs_id.in_(button_fs_ids)))))
def _get_quantity_to_invoice_timesheet(cls, works): pool = Pool() TimesheetLine = pool.get('timesheet.line') cursor = Transaction().connection.cursor() line = TimesheetLine.__table__() upto2tworks = defaultdict(list) twork2work = {} for work in works: upto = work.invoice_timesheet_up_to for timesheet_work in work.timesheet_works: twork2work[timesheet_work.id] = work.id upto2tworks[upto].append(timesheet_work.id) durations = defaultdict(datetime.timedelta) query = line.select(line.work, Sum(line.duration), group_by=line.work) for upto, tworks in upto2tworks.items(): for sub_ids in grouped_slice(tworks): query.where = (reduce_ids(line.work, sub_ids) & (line.invoice_line == Null)) if upto: query.where &= (line.date <= upto) cursor.execute(*query) for twork_id, duration in cursor: if duration: # SQLite uses float for SUM if not isinstance(duration, datetime.timedelta): duration = datetime.timedelta(seconds=duration) durations[twork2work[twork_id]] += duration quantities = {} for work in works: duration = durations[work.id] if work.list_price: hours = duration.total_seconds() / 60 / 60 if work.unit_to_invoice: hours = work.unit_to_invoice.round(hours) quantities[work.id] = hours return quantities
def __register__(cls, module_name): cursor = Transaction().connection.cursor() table = cls.__table_handler__(module_name) sql_table = cls.__table__() pool = Pool() Work = pool.get('timesheet.work') work = Work.__table__() created_company = not table.column_exist('company') super(Line, cls).__register__(module_name) # Migration from 3.4: new company field if created_company: # Don't use FROM because SQLite nor MySQL support it. cursor.execute(*sql_table.update( [sql_table.company], [work.select(work.company, where=work.id == sql_table.work)])) # Migration from 3.4: change hours into timedelta duration if table.column_exist('hours'): table.drop_constraint('check_move_hours_pos') cursor.execute(*sql_table.select(sql_table.id, sql_table.hours)) for id_, hours in cursor.fetchall(): duration = datetime.timedelta(hours=hours) cursor.execute( *sql_table.update([sql_table.duration], [duration], where=sql_table.id == id_)) table.drop_column('hours')
def _update_definitions(self, columns=None, indexes=None): if columns is None and indexes is None: columns = indexes = True cursor = Transaction().connection.cursor() # Fetch columns definitions from the table if columns: cursor.execute('PRAGMA table_info("' + self.table_name + '")') self._columns = {} for _, column, type_, notnull, hasdef, _ in cursor.fetchall(): column = re.sub(r'^\"|\"$', '', column) match = re.match(r'(\w+)(\((.*?)\))?', type_) if match: typname = match.group(1).upper() size = match.group(3) and int(match.group(3)) or 0 else: typname = type_.upper() size = -1 self._columns[column] = { 'notnull': notnull, 'hasdef': hasdef, 'size': size, 'typname': typname, } # Fetch indexes defined for the table if indexes: try: cursor.execute('PRAGMA index_list("' + self.table_name + '")') except IndexError: # There is sometimes IndexError cursor.execute('PRAGMA index_list("' + self.table_name + '")') self._indexes = [l[1] for l in cursor.fetchall()]
def __init__(self, model, module_name=None, history=False): super(TableHandler, self).__init__(model, module_name=module_name, history=history) self._columns = {} self._constraints = [] self._fkeys = [] self._indexes = [] self._model = model cursor = Transaction().connection.cursor() # Create new table if necessary if not self.table_exist(self.table_name): if not self.history: cursor.execute('CREATE TABLE `%s` (' 'id BIGINT AUTO_INCREMENT NOT NULL, ' 'PRIMARY KEY(id)' ') ENGINE=InnoDB;' % self.table_name) else: cursor.execute('CREATE TABLE `%s` (' '__id BIGINT AUTO_INCREMENT NOT NULL, ' 'id BIGINT, ' 'PRIMARY KEY(__id)' ') ENGINE=InnoDB;' % self.table_name) self._update_definitions(columns=True) if 'id' not in self._columns: if not self.history: cursor.execute('ALTER TABLE `%s` ' 'ADD COLUMN id BIGINT AUTO_INCREMENT ' 'NOT NULL PRIMARY KEY' % self.table_name) else: cursor.execute('ALTER TABLE `%s` ' 'ADD COLUMN id BIGINT' % self.table_name) self._update_definitions(columns=True) if self.history and '__id' not in self._columns: cursor.execute('ALTER TABLE `%s` ' 'ADD COLUMN __id BIGINT AUTO_INCREMENT ' 'NOT NULL PRIMARY KEY' % self.table_name) self._update_definitions()
def alter_size(self, column_name, column_type): cursor = Transaction().connection.cursor() cursor.execute("ALTER TABLE \"%s\" " "RENAME COLUMN \"%s\" TO _temp_change_size" % (self.table_name, column_name)) cursor.execute("ALTER TABLE \"%s\" " "ADD COLUMN \"%s\" %s" % (self.table_name, column_name, column_type)) cursor.execute("UPDATE \"%s\" " "SET \"%s\" = _temp_change_size::%s" % (self.table_name, column_name, column_type)) cursor.execute("ALTER TABLE \"%s\" " "DROP COLUMN _temp_change_size" % (self.table_name, )) self._update_definitions(columns=True)
def change_loan_installment(cls, records, values): """Change number of installments pending for loan""" cursor = Transaction().connection.cursor() LoanLine = Pool().get('computer.loan.line') for loan in records: cursor.execute( 'SELECT sum(amount) FROM computer_loan_line WHERE loan=%s \ AND status = %s', (loan.id, 'done')) total_amount = cursor.fetchone() if total_amount[0]: reschedule = loan.amount_required - total_amount[0] cls.write(records, { 'payout': total_amount[0], 'reschedule': reschedule }) amount = (reschedule / values['installment_no']) else: amount = (loan.amount_required / values['installment_no']) cursor.execute( 'delete FROM computer_loan_line WHERE loan=%s \ AND status != %s', (loan.id, 'done')) count = 0 for line in range(1, int(values['installment_no']) + 1): mydate = datetime.datetime.now().month month = mydate - 1 if month + line > 12: count += 1 if count > 12: count = 1 months = datetime.date(1900, count, 1).strftime('%B') else: months = datetime.date(1900, month + line, 1).strftime('%B') vals = { 'month': months, 'amount': amount, 'status': 'pending', 'loan': loan.id } line = LoanLine.create([vals])
def _update_definitions(self, columns=None, constraints=None, indexes=None): if columns is None and constraints is None and indexes is None: columns = constraints = indexes = True cursor = Transaction().connection.cursor() if columns: self._columns = {} # Fetch columns definitions from the table cursor.execute('SELECT ' 'column_name, udt_name, is_nullable, ' 'character_maximum_length, ' 'column_default ' 'FROM information_schema.columns ' 'WHERE table_name = %s AND table_schema = %s', (self.table_name, self.table_schema)) for column, typname, nullable, size, default in cursor.fetchall(): self._columns[column] = { 'typname': typname, 'notnull': True if nullable == 'NO' else False, 'size': size, 'default': default, } if constraints: # fetch constraints for the table cursor.execute('SELECT constraint_name ' 'FROM information_schema.table_constraints ' 'WHERE table_name = %s AND table_schema = %s', (self.table_name, self.table_schema)) self._constraints = [c for c, in cursor.fetchall()] cursor.execute('SELECT k.column_name, r.delete_rule ' 'FROM information_schema.key_column_usage AS k ' 'JOIN information_schema.referential_constraints AS r ' 'ON r.constraint_schema = k.constraint_schema ' 'AND r.constraint_name = k.constraint_name ' 'WHERE k.table_name = %s AND k.table_schema = %s', (self.table_name, self.table_schema)) self._fk_deltypes = dict(cursor.fetchall()) if indexes: # Fetch indexes defined for the table cursor.execute("SELECT cl2.relname " "FROM pg_index ind " "JOIN pg_class cl on (cl.oid = ind.indrelid) " "JOIN pg_namespace n ON (cl.relnamespace = n.oid) " "JOIN pg_class cl2 on (cl2.oid = ind.indexrelid) " "WHERE cl.relname = %s AND n.nspname = %s", (self.table_name, self.table_schema)) self._indexes = [l[0] for l in cursor.fetchall()]
def __register__(cls, module_name): cursor = Transaction().connection.cursor() property_table = 'ir_property' pos_sequence_table = cls._table TableHandler = backend.get('TableHandler') table = TableHandler(cls, module_name) exist = table.column_exist('invoice_sequence') super(PosSequence, cls).__register__(module_name) # Migration from 4.2: set invoice_sequence if not exist and TableHandler.table_exist(property_table): cursor.execute('UPDATE "' + pos_sequence_table + '" ' 'SET invoice_sequence = (' 'SELECT split_part(value, \',\', 2) ' 'FROM "' + property_table + '" ' 'WHERE split_part(res, \',\', 1) = ' '\'account.pos.sequence\' ' 'AND split_part(res, \',\', 2)::INTEGER = ' '"' + pos_sequence_table + '".id' ')::INTEGER')
def __init__(self, model, module_name=None, history=False): super(TableHandler, self).__init__(model, module_name=module_name, history=history) self._columns = {} self._constraints = [] self._fk_deltypes = {} self._indexes = [] self._model = model cursor = Transaction().connection.cursor() # Create new table if necessary if not self.table_exist(self.table_name): if not self.history: cursor.execute('CREATE TABLE "%s" ' '(id INTEGER PRIMARY KEY AUTOINCREMENT)' % self.table_name) else: cursor.execute('CREATE TABLE "%s" ' '(__id INTEGER PRIMARY KEY AUTOINCREMENT, ' 'id INTEGER)' % self.table_name) self._update_definitions()
def get_population(cls, date1, date2, gender, total): """ Return Total Number of living people in the system segmented by age group and gender""" cursor = Transaction().connection.cursor() if (total): cursor.execute( "SELECT COUNT(id) \ FROM party_party WHERE \ gender = %s and deceased is not TRUE", (gender)) else: cursor.execute( "SELECT COUNT(id) \ FROM party_party \ WHERE dob BETWEEN %s and %s AND \ gender = %s \ and deceased is not TRUE", (date2, date1, gender)) res = cursor.fetchone()[0] return (res)
def change_gpf_installment(cls, records, values): cursor = Transaction().connection.cursor() GPFLine = Pool().get('gpf.advance.line') for gpf in records: cursor.execute( 'SELECT sum(amount) FROM gpf_advance_line WHERE gpf_advance=%s \ AND status = %s', (gpf.id, 'done')) total_amount = cursor.fetchone() if total_amount[0]: reschedule = gpf.amount_required - total_amount[0] cls.write(records, { 'payout': total_amount[0], 'reschedule': reschedule }) amount = (reschedule / values['installment_no']) else: amount = (gpf.amount_required / values['installment_no']) cursor.execute( 'delete FROM gpf_advance_line WHERE gpf_advance=%s \ AND status != %s', (gpf.id, 'done')) count = 0 for line in range(1, int(values['installment_no']) + 1): mydate = datetime.datetime.now().month month = mydate - 1 if month + line > 12: count += 1 if count > 12: count = 1 months = datetime.date(1900, count, 1).strftime('%B') else: months = datetime.date(1900, month + line, 1).strftime('%B') vals = { 'month': months, 'amount': amount, 'status': 'pending', 'gpf_advance': gpf.id } line = GPFLine.create([vals])
def __register__(cls, module_name): pool = Pool() AccountEntry = pool.get('analytic.account.entry') cursor = Transaction().connection.cursor() super(AnalyticMixin, cls).__register__(module_name) handler = cls.__table_handler__(module_name) # Migration from 3.4: analytic accounting changed to reference field if handler.column_exist('analytic_accounts'): entry = AccountEntry.__table__() table = cls.__table__() cursor.execute( *table.select(table.id, table.analytic_accounts, where=table.analytic_accounts != None)) for line_id, selection_id in cursor.fetchall(): cursor.execute( *entry.update(columns=[entry.origin], values=['%s,%s' % (cls.__name__, line_id)], where=entry.selection == selection_id)) handler.drop_column('analytic_accounts')
def __register__(cls, module_name): pool = Pool() Sale = pool.get('sale.sale') cursor = Transaction().connection.cursor() TableHandler = backend.get('TableHandler') sql_table = cls.__table__() sale = Sale.__table__() table = TableHandler(cls, module_name) number_exists = table.column_exist('number') # Migration from 3.8: rename reference into number if table.column_exist('reference') and not number_exists: table.column_rename('reference', 'number') number_exists = True super(SaleOpportunity, cls).__register__(module_name) table = TableHandler(cls, module_name) # Migration from 2.8: make party not required and add number as # required table.not_null_action('party', action='remove') if not number_exists: cursor.execute(*sql_table.update(columns=[sql_table.number], values=[sql_table.id], where=sql_table.number == Null)) table.not_null_action('number', action='add') # Migration from 3.4: replace sale by origin if table.column_exist('sale'): cursor.execute(*sql_table.select( sql_table.id, sql_table.sale, where=sql_table.sale != Null)) for id_, sale_id in cursor.fetchall(): cursor.execute( *sale.update(columns=[sale.origin], values=['%s,%s' % (cls.__name__, id_)], where=sale.id == sale_id)) table.drop_column('sale', exception=True) # Migration from 4.0: change probability into conversion probability if table.column_exist('probability'): cursor.execute( *sql_table.update([sql_table.conversion_probability], [sql_table.probability / 100.0])) table.drop_constraint('check_percentage') table.drop_column('probability') # Migration from 4.2: make employee not required table.not_null_action('employee', action='remove')
def _add_raw_column(self, column_name, column_type, default=None, field_size=None, string=''): if self.column_exist(column_name): base_type = column_type[0].upper() if base_type != self._columns[column_name]['typname']: if (self._columns[column_name]['typname'], base_type) in [ ('VARCHAR', 'TEXT'), ('TEXT', 'VARCHAR'), ('DATE', 'TIMESTAMP'), ('INTEGER', 'FLOAT'), ('INTEGER', 'NUMERIC'), ('FLOAT', 'NUMERIC'), ]: self.alter_type(column_name, base_type) else: logger.warning( 'Unable to migrate column %s on table %s ' 'from %s to %s.', column_name, self.table_name, self._columns[column_name]['typname'], base_type) if (base_type == 'VARCHAR' and self._columns[column_name]['typname'] == 'VARCHAR'): # Migrate size from_size = self._columns[column_name]['size'] if field_size is None: if from_size > 0: self.alter_size(column_name, base_type) elif from_size == field_size: pass elif from_size and from_size < field_size: self.alter_size(column_name, column_type[1]) else: logger.warning( 'Unable to migrate column %s on table %s ' 'from varchar(%s) to varchar(%s).', column_name, self.table_name, from_size if from_size and from_size > 0 else "", field_size) return cursor = Transaction().connection.cursor() column_type = column_type[1] cursor.execute(('ALTER TABLE %s ADD COLUMN %s %s') % ( _escape_identifier(self.table_name), _escape_identifier(column_name), column_type)) if default: # check if table is non-empty: cursor.execute('SELECT 1 FROM %s limit 1' % _escape_identifier(self.table_name)) if cursor.fetchone(): # Populate column with default values: cursor.execute('UPDATE ' + _escape_identifier(self.table_name) + ' SET ' + _escape_identifier(column_name) + ' = ?', (default(),)) self._update_definitions(columns=True)
def get_deposit(cls, parties, name): pool = Pool() MoveLine = pool.get('account.move.line') Account = pool.get('account.account') User = pool.get('res.user') cursor = Transaction().connection.cursor() line = MoveLine.__table__() account = Account.__table__() values = {p.id: 0 for p in parties} user = User(Transaction().user) if not user.company: return values currency = user.company.currency line_clause, _ = MoveLine.query_get(line) for sub_parties in grouped_slice(parties): party_clause = reduce_ids(line.party, [p.id for p in sub_parties]) cursor.execute(*line.join( account, condition=account.id == line.account).select( line.party, # Use credit - debit to positive deposit amount Sum(Coalesce(line.credit, 0) - Coalesce(line.debit, 0)), where=account.active & (account.kind == 'deposit') & party_clause & (line.reconciliation == Null) & (account.company == user.company.id) & line_clause, group_by=line.party)) for party_id, value in cursor.fetchall(): # SQLite uses float for SUM if not isinstance(value, Decimal): value = currency.round(Decimal(str(value))) values[party_id] = value return values
def __register__(cls, module): table_h = cls.__table_handler__(module) cursor = Transaction().connection.cursor() table = cls.__table__() # Migration from 5.8: rename cost into cost_sale if (table_h.column_exist('cost') and not table_h.column_exist('cost_sale')): table_h.column_rename('cost', 'cost_sale') if (table_h.column_exist('cost_currency') and not table_h.column_exist('cost_sale_currency')): table_h.column_rename('cost_currency', 'cost_sale_currency') cost_method_exists = table_h.column_exist('cost_method') super().__register__(module) # Migration from 6.0: fill new cost_method field if not cost_method_exists: cursor.execute(*table.update( columns=[table.cost_method], values=['shipment']))
def create(self, vals): later = {} vals = vals.copy() cursor = Transaction().cursor for field in vals: if field in self._columns\ and hasattr(self._columns[field], 'set'): later[field] = vals[field] for field in later: del vals[field] if cursor.nextid(self._table): cursor.setnextid(self._table, cursor.currid(self._table)) new_id = super(DocumentInvoiceGoods, self).create( vals) invoice = self.browse( new_id) new_id = invoice.document.id cr = Transaction().cursor cr.execute('UPDATE "' + self._table + '" SET id = %s '\ 'WHERE id = %s', (invoice.document.id, invoice.id)) ModelStorage.delete(self, invoice.id) self.write( new_id, later) res = self.browse( new_id) return res.id
def get_plants_list(cls, reports, name): cursor = Transaction().connection.cursor() pool = Pool() Plant = pool.get('lims.plant') Equipment = pool.get('lims.equipment') Sample = pool.get('lims.sample') Fraction = pool.get('lims.fraction') Notebook = pool.get('lims.notebook') ResultsSample = pool.get('lims.results_report.version.detail.sample') ResultsDetail = pool.get('lims.results_report.version.detail') ResultsVersion = pool.get('lims.results_report.version') result = {} for r in reports: result[r.id] = '' cursor.execute( 'SELECT DISTINCT(p.name) ' 'FROM "' + Plant._table + '" p ' 'INNER JOIN "' + Equipment._table + '" e ' 'ON p.id = e.plant ' 'INNER JOIN "' + Sample._table + '" s ' 'ON e.id = s.equipment ' 'INNER JOIN "' + Fraction._table + '" f ' 'ON s.id = f.sample ' 'INNER JOIN "' + Notebook._table + '" n ' 'ON f.id = n.fraction ' 'INNER JOIN "' + ResultsSample._table + '" rs ' 'ON n.id = rs.notebook ' 'INNER JOIN "' + ResultsDetail._table + '" rd ' 'ON rs.version_detail = rd.id ' 'INNER JOIN "' + ResultsVersion._table + '" rv ' 'ON rd.report_version = rv.id ' 'WHERE rv.results_report = %s ' 'AND rd.state != \'annulled\' ' 'ORDER BY p.name', (r.id, )) samples = [x[0] for x in cursor.fetchall()] if samples: result[r.id] = ', '.join(samples) return result
def __register__(cls, module_name): pool = Pool() ModelData = pool.get('ir.model.data') Purchase = pool.get('purchase.purchase') PurchaseLine = pool.get('purchase.line') TableHandler = backend.get('TableHandler') model_data = ModelData.__table__() purchase = Purchase.__table__() purchase_line = PurchaseLine.__table__() request = cls.__table__() tablehandler = TableHandler(cls, module_name) state_exist = tablehandler.column_exist('state') super(PurchaseRequest, cls).__register__(module_name) # Migration from 3.6: removing the constraint on the quantity tablehandler = TableHandler(cls, module_name) tablehandler.drop_constraint('check_purchase_request_quantity') # Migration from 3.8: renaming module of Purchase Request group entry cursor = Transaction().connection.cursor() cursor.execute(*model_data.update( columns=[model_data.module], values=['purchase_request'], where=((model_data.fs_id == 'group_purchase_request') & (model_data.module == 'stock_supply')))) # Migration from 4.0: remove required on product and uom tablehandler.not_null_action('product', action='remove') tablehandler.not_null_action('uom', action='remove') # Migration from 4.2: add state if not state_exist: cursor = Transaction().connection.cursor() update = Transaction().connection.cursor() query = request.join(purchase_line, type_='INNER', condition=request.purchase_line == purchase_line.id ).join(purchase, type_='INNER', condition=purchase_line.purchase == purchase.id ).select( request.id, purchase.state, request.exception_ignored) cursor.execute(*query) for request_id, purchase_state, exception_ignored in cursor: if purchase_state == 'cancel' and not exception_ignored: state = 'exception' elif purchase_state == 'cancel': state = 'cancel' elif purchase_state == 'done': state = 'done' else: state = 'purchased' update.execute(*request.update( [request.state], [state], where=request.id == request_id)) # Migration from 4.4: remove required on origin tablehandler.not_null_action('origin', action='remove')
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor pool = Pool() ModelData = pool.get('ir.model.data') model_data = ModelData.__table__() # Migration from 3.6: remove double module old_table = 'ir_module_module_config_wizard_item' if TableHandler.table_exist(cursor, old_table): TableHandler.table_rename(cursor, old_table, cls._table) cursor.execute(*model_data.update( columns=[model_data.model], values=[cls.__name__], where=(model_data.model == 'ir.module.module.config_wizard.item'))) table = TableHandler(cursor, cls, module_name) # Migrate from 2.2 remove name table.drop_column('name') super(ModuleConfigWizardItem, cls).__register__(module_name)
def __register__(cls, module_name): cursor = Transaction().connection.cursor() model_data = Table('ir_model_data') model = Table('ir_model') # Migration from 1.2: packing renamed into shipment cursor.execute(*model_data.update( columns=[model_data.fs_id], values=[ Overlay(model_data.fs_id, 'shipment', Position('packing', model_data.fs_id), len('packing')) ], where=model_data.fs_id.like('%packing%') & (model_data.module == module_name))) cursor.execute(*model.update( columns=[model.model], values=[ Overlay(model.model, 'shipment', Position('packing', model.model), len('packing')) ], where=model.model.like('%packing%') & (model.module == module_name))) super(ShipmentInternal, cls).__register__(module_name)
def restore_default_party_lang_from_4_2(cls): from trytond.transaction import Transaction from sql import Null, Table, Cast from sql.operators import Concat from trytond.pool import Pool TableHandler = backend.get('TableHandler') if not TableHandler.table_exist('ir_property'): return pool = Pool() property = Table('ir_property') Lang = pool.get('ir.lang') field = pool.get('ir.model.field').__table__() lang = Lang.__table__() cursor = Transaction().connection.cursor() query_table = property.join( lang, condition=(property.value == Concat( 'ir.lang,', Cast(lang.id, 'VARCHAR')))).join(field, condition=((property.field == field.id) & (field.name == 'lang'))) cursor.execute( *query_table.select(lang.id, where=property.res == Null)) result = cursor.fetchone() if result: result = list(result) default_lang = Lang(result[0]) print 'Default Language restored [%s]' % default_lang.rec_name pool.get('party.configuration.party_lang').create([{ 'party_lang': default_lang }]) else: print 'No default language on party configuration found'
def setup(cls): cursor = Transaction().connection.cursor() if backend.name != 'postgresql': raise Exception('Database must be postgresql !') # Check for test table table = Table('tables', 'information_schema') for schema in Transaction().database.search_path: cursor.execute( *table.select(Literal(1), where=(table.table_name == 'benchmark_table') & (table.table_schema == schema))) if cursor.rowcount: raise Exception('Benchmark table already in, run ' 'teardown and try again') # Create table cursor.execute('CREATE TABLE "benchmark_table" (' 'id integer PRIMARY KEY,' 'some_string varchar(100),' 'some_date date)')
def create(self, vals): later = {} vals = vals.copy() cr = Transaction().cursor for field in vals: if field in self._columns\ and hasattr(self._columns[field], 'set'): later[field] = vals[field] for field in later: del vals[field] vals['state'] = 'draft' if cr.nextid(self._table): cr.setnextid(self._table, cr.currid(self._table)) new_id = super(DocumentCash, self).create(vals) cash = self.browse(new_id) new_id = cash.document.id cr.execute('UPDATE "' + self._table + '" SET id = %s '\ 'WHERE id = %s', (cash.document.id, cash.id)) ModelStorage.delete(self, cash.id) self.write(new_id, later) res = self.browse(new_id) return res.id
def __register__(cls, module_name): cursor = Transaction().connection.cursor() pool = Pool() ModelData = pool.get('ir.model.data') model_data = ModelData.__table__() # Migration from 3.6: remove double module old_table = 'ir_module_module_config_wizard_item' if backend.TableHandler.table_exist(old_table): backend.TableHandler.table_rename(old_table, cls._table) cursor.execute(*model_data.update( columns=[model_data.model], values=[cls.__name__], where=(model_data.model == 'ir.module.module.config_wizard.item'))) super(ModuleConfigWizardItem, cls).__register__(module_name) table = cls.__table_handler__(module_name) # Migration from 5.0: remove required on sequence table.not_null_action('sequence', 'remove')
def uninstall(cls, modules): pool = Pool() Module = pool.get('ir.module') Dependency = pool.get('ir.module.dependency') module_table = Module.__table__() dep_table = Dependency.__table__() cursor = Transaction().cursor for module in modules: cursor.execute(*dep_table.join( module_table, condition=(dep_table.module == module_table.id)).select( module_table.state, module_table.name, where=(dep_table.name == module.name) & NotIn(module_table.state, ['uninstalled', 'to remove']))) res = cursor.fetchall() if res: cls.raise_user_error('uninstall_dep', error_description='\n'.join('\t%s: %s' % (x[0], x[1]) for x in res)) cls.write(modules, {'state': 'to remove'})
def get_unread(cls, ids, name): pool = Pool() Read = pool.get('ir.note.read') cursor = Transaction().connection.cursor() user_id = Transaction().user table = cls.__table__() read = Read.__table__() unread = {} for sub_ids in grouped_slice(ids): where = reduce_ids(table.id, sub_ids) query = table.join(read, 'LEFT', condition=(table.id == read.note) & (read.user == user_id)).select( table.id, Case((read.user != Null, False), else_=True), where=where) cursor.execute(*query) unread.update(cursor.fetchall()) return unread
def do_update(self, action): pool = Pool() Translation = pool.get('ir.translation') cursor = Transaction().cursor lang = self.start.language.code translation = Translation.__table__() types = ['nereid_template', 'wtforms', 'nereid'] columns = [ translation.name.as_('name'), translation.res_id.as_('res_id'), translation.type.as_('type'), translation.src.as_('src'), translation.module.as_('module'), translation.comments.as_('comments'), ] cursor.execute(*(translation.select(*columns, where=(translation.lang == 'en_US') & translation.type.in_(types)) - translation.select(*columns, where=(translation.lang == lang) & translation.type.in_(types)))) to_create = [] for row in cursor.dictfetchall(): to_create.append({ 'name': row['name'], 'res_id': row['res_id'], 'lang': lang, 'type': row['type'], 'src': row['src'], 'module': row['module'], 'comments': row['comments'], }) if to_create: with Transaction().set_user(0): Translation.create(to_create) return super(TranslationUpdate, self).do_update(action)
def get_listings_to_export_inventory(self): """ This method returns listing, which needs inventory update Downstream module can override change its implementation :return: List of AR of `product.product.channel_listing` """ ChannelListing = Pool().get('product.product.channel_listing') cursor = Transaction().cursor if not self.last_inventory_export_time: # Return all active listings return ChannelListing.search([('channel', '=', self), ('state', '=', 'active')]) else: # Query to find listings # in which product inventory is recently updated or # listing it self got updated recently cursor.execute( """ SELECT listing.id FROM product_product_channel_listing AS listing INNER JOIN stock_move ON stock_move.product = listing.product WHERE listing.channel = %s AND listing.state = 'active' AND ( COALESCE(stock_move.write_date, stock_move.create_date) > %s OR COALESCE(listing.write_date, listing.create_date) > %s ) GROUP BY listing.id """, ( self.id, self.last_inventory_export_time, self.last_inventory_export_time, )) listing_ids = map(lambda r: r[0], cursor.fetchall()) return ChannelListing.browse(listing_ids)