Passa al contenuto
Odoo Menu
  • Accedi
  • Provalo gratis
  • App
    Finanze
    • Contabilità
    • Fatturazione
    • Note spese
    • Fogli di calcolo (BI)
    • Documenti
    • Firma
    Vendite
    • CRM
    • Vendite
    • Punto vendita Negozio
    • Punto vendita Ristorante
    • Abbonamenti
    • Noleggi
    Siti web
    • Configuratore sito web
    • E-commerce
    • Blog
    • Forum
    • Live chat
    • E-learning
    Supply chain
    • Magazzino
    • Produzione
    • PLM
    • Acquisti
    • Manutenzione
    • Qualità
    Risorse umane
    • Dipendenti
    • Assunzioni
    • Ferie
    • Valutazioni
    • Referral dipendenti
    • Parco veicoli
    Marketing
    • Social marketing
    • E-mail marketing
    • SMS marketing
    • Eventi
    • Marketing automation
    • Sondaggi
    Servizi
    • Progetti
    • Fogli ore
    • Assistenza sul campo
    • Helpdesk
    • Pianificazione
    • Appuntamenti
    Produttività
    • Comunicazioni
    • Approvazioni
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    App di terze parti Odoo Studio Piattaforma cloud Odoo
  • Settori
    Retail
    • Libreria
    • Negozio di abbigliamento
    • Negozio di arredamento
    • Alimentari
    • Ferramenta
    • Negozio di giocattoli
    Cibo e ospitalità
    • Bar e pub
    • Ristorante
    • Fast food
    • Pensione
    • Grossista di bevande
    • Hotel
    Agenzia immobiliare
    • Agenzia immobiliare
    • Studio di architettura
    • Edilizia
    • Gestione immobiliare
    • Impresa di giardinaggio
    • Associazione di proprietari immobiliari
    Consulenza
    • Società di contabilità
    • Partner Odoo
    • Agenzia di marketing
    • Studio legale
    • Selezione del personale
    • Audit e certificazione
    Produzione
    • Tessile
    • Metallo
    • Arredamenti
    • Alimentare
    • Birrificio
    • Ditta di regalistica aziendale
    Benessere e sport
    • Club sportivo
    • Negozio di ottica
    • Centro fitness
    • Centro benessere
    • Farmacia
    • Parrucchiere
    Commercio
    • Tuttofare
    • Hardware e assistenza IT
    • Ditta di installazione di pannelli solari
    • Calzolaio
    • Servizi di pulizia
    • Servizi di climatizzazione
    Altro
    • Organizzazione non profit
    • Ente per la tutela ambientale
    • Agenzia di cartellonistica pubblicitaria
    • Studio fotografico
    • Punto noleggio di biciclette
    • Rivenditore di software
    Carica tutti i settori
  • Community
    Apprendimento
    • Tutorial
    • Documentazione
    • Certificazioni 
    • Formazione
    • Blog
    • Podcast
    Potenzia la tua formazione
    • Programma educativo
    • Scale Up! Business Game
    • Visita Odoo
    Ottieni il software
    • Scarica
    • Versioni a confronto
    • Note di versione
    Collabora
    • Github
    • Forum
    • Eventi
    • Traduzioni
    • Diventa nostro partner
    • Servizi per partner
    • Registra la tua società di contabilità
    Ottieni servizi
    • Trova un partner
    • Trova un contabile
    • Incontra un esperto
    • Servizi di implementazione
    • Testimonianze dei clienti
    • Supporto
    • Aggiornamenti
    GitHub Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Richiedi una demo
  • Prezzi
  • Aiuto

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilità
  • Magazzino
  • PoS
  • Progetti
  • MRP
All apps
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
Assistenza

How can i execute a SQL statement on module update and installation?

Iscriviti

Ricevi una notifica quando c'è un'attività per questo post

La domanda è stata contrassegnata
developmentinstallationmoduleupdatesql
7 Risposte
68215 Visualizzazioni
Avatar
herbert6453

How can i execute a SQL statement after module installation and a different sql statement after every modul update?

12
Avatar
Abbandona
Avatar
Daniel Reis
Risposta migliore

You can execute Model's method upon module's install or upgrade. Here's an example:

First, add the method that will do the initialization actions. For example:

class crm_routing_users(osv.osv):
"""For each Department and Role, which user is the responsible"""
_name = "crm.routing.users"

def _migrate_from_project_issue_profiling(self, cr, uid, ids=None, context=None):
"""Migrate from project.issue.profiling. since this module can completely replace it."""
if ids is not None:
raise NotImplementedError("Ids is just there by convention! Please don't use it.")
cr.execute("select exists(select * from information_schema.tables " "where table_name=project_issue_profiling)")
if cr.fetchone()[0]:
cr.execute(""" INSERT INTO crm_routing_users ( create_uid, create_date, write_date, write_uid, notes, user_id, section_id, department_id) SELECT create_uid, create_date, write_date, write_uid, notes, user_id, section_id, department_id FROM project_issue_profiling""")
_logger.info("Successful data copy from project.issue.profiling to crm.routing.users")
return True

Next, declare the call in an XML data file:

<openerp>
<data>
<!-- Migration for "project_service_profiling". Can be skipped if that module is not in use. -->
<function model="crm.routing.users" name="_migrate_from_project_issue_profiling"/>
</data>
</openerp>

EDIT:

Finally, add the XML data file to tour _openerp_.py manifest, in the data (v7) section. If you want it to run only on first install, add noupdate="1" to the data tag.

17
Avatar
Abbandona
Mohammad Alhashash

Are you sure there could be an init section in module manifest? Please check my comment on GEM's answer below. I think there is not init section and there is no difference between xml declaration using init_xml and update_xml attributes. At least in v7.0. Using noupdate="1" on data tag will run function tags only at module install.

Avatar
Cyril Gaspard (GEM)
Risposta migliore

Hi,

for the answer just create a file.sql with your requests inside, exemple :

DELETE FROM ir_ui_view_sc WHERE user_id = 1 and name = 'Clients';

add in your module_name/__openerp__.py :

in section

'update_xml': ["file.sql",],

for v7 :

'data': ["file.sql",],

use insert , update ... Bye

5
Avatar
Abbandona
Mohammad Alhashash

Regarding .xml and .sql files, there is no difference between module attributes init_xml, update_xml and data. The file will always be updated/executed on any module installation or update. Check the load_module_graph() function in openerp/modules/loading.py

Avatar
Mohammad Alhashash
Risposta migliore

You can create a method init(self, cr) in your model and it will be called upon module installation or upgrade.

You can check for update or install mode by checking the the existence of data or structures that should have been created in initialization or you can just use common sql or replace mechanism to use the same sql for both states.

Most reports use this method to create required views. Check this example from addons/account/report/account_report:

class report_account_receivable(osv.osv):
    _name = "report.account.receivable"
    _description = "Receivable accounts"
    _auto = False
    _columns = {
        'name': fields.char('Week of Year', size=7, readonly=True),
        'type': fields.selection(_code_get, 'Account Type', required=True),
        'balance':fields.float('Balance', readonly=True),
        'debit':fields.float('Debit', readonly=True),
        'credit':fields.float('Credit', readonly=True),
    }
    _order = 'name desc'

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'report_account_receivable')
        cr.execute("""
            create or replace view report_account_receivable as (
                select
                    min(l.id) as id,
                    to_char(date,'YYYY:IW') as name,
                    sum(l.debit-l.credit) as balance,
                    sum(l.debit) as debit,
                    sum(l.credit) as credit,
                    a.type
                from
                    account_move_line l
                left join
                    account_account a on (l.account_id=a.id)
                where
                    l.state <> 'draft'
                group by
                    to_char(date,'YYYY:IW'), a.type
            )""")
3
Avatar
Abbandona
david

I have just to create report by using sql query (the same with above). But I have the problem: If I execute the query by postgreSQL maestro, there are 600 records. By postgreSQL Maestro, I open the view there are also 600 records. But the tree view in Openerp V7 there are only 19 records. Anyone help me?

Avatar
Yurdik Cervantes Mendoza
Risposta migliore

As long as we write less SQL sentences, the ORM can make more optimizations for us in the future and the maintenance will be easier.

There are cases where you have made strong changes to your models already used in production and the ORM can't make the automatic inference of the sql statements needed to give the database a logical state corresponding to your new code (ex: fix your table structure, move data between columns, calculate quickly default values for new not null columns using sql expressions, etc..).If your case is one of those data maintenance problems, you can use the migration scripts as specified in the MigrationManager descriptions: http://bit.ly/1UqiO8h.This mechanism is used extensively inside openupgrade: http://bit.ly/1QDc40R  You can find a lot of samples there.

In your case, just create a migration folder with a -pre or -post update script:

            <moduledir>
`-- migrations
|-- 8.0
| |-- pre-migration.py

In the  pre-migration.py script you can check the version and put both queries. The first two digits passed to the script is always the odoo version the others come from your module version ( __openerp__.py of your module)

You can install the module specifying one version 1.1 and then change the module version to 1.2, 1.3, etc... in

def migrate(cr, version):
if version == '8.0.1.1':
  cr.execute("""UPDATE ... FROM account_analytic_journal WHERE .... """)
else
  cr.execute(anothersql)

1
Avatar
Abbandona
Ti stai godendo la conversazione? Non leggere soltanto, partecipa anche tu!

Crea un account oggi per scoprire funzionalità esclusive ed entrare a far parte della nostra fantastica community!

Registrati
Post correlati Risposte Visualizzazioni Attività
Merge Two Or More Modules Into One (V11+)
development modules module sql v11.0
Avatar
0
feb 21
4029
How implement a user query dialog "use init data yes or no" during module installation and update?
installation module data update init
Avatar
0
mar 15
4913
how can I resolve dependency for Module called unidecode? Risolto
installation module
Avatar
Avatar
Avatar
Avatar
Avatar
6
set 24
53697
How to run a python function right after installing a module?
installation module
Avatar
2
giu 20
21115
Should I update modules individually after git update? Risolto
module update
Avatar
Avatar
1
mar 18
5449
Community
  • Tutorial
  • Documentazione
  • Forum
Open source
  • Scarica
  • Github
  • Runbot
  • Traduzioni
Servizi
  • Hosting Odoo.sh
  • Supporto
  • Aggiornamenti
  • Sviluppi personalizzati
  • Formazione
  • Trova un contabile
  • Trova un partner
  • Diventa nostro partner
Chi siamo
  • La nostra azienda
  • Branding
  • Contattaci
  • Lavora con noi
  • Eventi
  • Podcast
  • Blog
  • Clienti
  • Note legali • Privacy
  • Sicurezza
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo è un gestionale di applicazioni aziendali open source pensato per coprire tutte le esigenze della tua azienda: CRM, Vendite, E-commerce, Magazzino, Produzione, Fatturazione elettronica, Project Management e molto altro.

Il punto di forza di Odoo è quello di offrire un ecosistema unico di app facili da usare, intuitive e completamente integrate tra loro.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now