add sql modules into admin site
351555
def admin(module):
    """"""
    # add module into admin site
    app = os.getcwd().split('/')[-1]
    if app != 'app':
        logger.warning('''\033[31m{Warning}\033[0m
==> your current path is \033[32m%s\033[0m\n
==> please add your sql module under app folder!''' % os.getcwd())
        exit(1)

    admin_path = os.path.join(os.getcwd(), 'admin')
    os.chdir(admin_path)
    with open('views.py', 'r+') as f:
        prev = pos = 0
        while f.readline():
            prev, pos = pos, f.tell()
        f.seek(prev)
        f.write(
            '\nfrom app.models import %s\nadmin.add_view(ModelView(%s, db.session))'
            % (module, module)
        )

    logger.info('''\033[33m{Info}\033[0m: add module done!''')
1270420
def setup_db(session, botconfig, confdir):
    """"""
    Base.metadata.create_all(session.connection())
    # If we're creating a fresh db, we don't need to worry about migrations.
    if not session.get_bind().has_table('alembic_version'):
        conf_obj = config.Config()
        conf_obj.set_main_option('bot_config_path', confdir)
        with resources.path('cslbot', botconfig['alembic']['script_location']) as script_location:
            conf_obj.set_main_option('script_location', str(script_location))
            command.stamp(conf_obj, 'head')

    # Populate permissions table with owner.
    owner_nick = botconfig['auth']['owner']
    if not session.query(Permissions).filter(Permissions.nick == owner_nick).count():
        session.add(Permissions(nick=owner_nick, role='owner'))
955686
def add_column_options!(sql, options)
      options.delete(:default) if options.has_key?(:default) && options[:default].nil?
      options.delete(:null) if options.has_key?(:null) && (options[:null].nil? || options[:null] == true)
      super
    end
42061
def bootstrap(command, conf, vars):
    """"""

    # <websetup.bootstrap.before.auth
    from sqlalchemy.exc import IntegrityError
    try:
        u = model.User()
        u.user_name = 'manager'
        u.display_name = 'Example manager'
        u.email_address = 'manager@somedomain.com'
        u.password = 'managepass'
    
        model.DBSession.add(u)
    
        g = model.Group()
        g.group_name = 'managers'
        g.display_name = 'Managers Group'
    
        g.users.append(u)
    
        model.DBSession.add(g)
    
        p = model.Permission()
        p.permission_name = 'manage'
        p.description = 'This permission give an administrative right to the bearer'
        p.groups.append(g)
    
        model.DBSession.add(p)
    
        u1 = model.User()
        u1.user_name = 'editor'
        u1.display_name = 'Example editor'
        u1.email_address = 'editor@somedomain.com'
        u1.password = 'editpass'
    
        model.DBSession.add(u1)
        model.DBSession.flush()
        transaction.commit()
    except IntegrityError:
        print('Warning, there was a problem adding your auth data, it may have already been added:')
        import traceback
        print(traceback.format_exc())
        transaction.abort()
        print('Continuing with bootstrapping...')
477867
public static void addSupport(AbstractModule module) {
        module.bindInstance(SQLCodegenModule.ENTITYPATH_TYPE, RelationalPathSpatial.class);
        registerTypes(module.get(Configuration.class));
        registerTypes(module.get(TypeMappings.class));
        addImports(module);
    }
964956
function install() {
    global $db, $messageStack;
    if (defined('MODULE_PAYMENT_PAYPALDP_STATUS')) {
      $messageStack->add_session('Website Payments Pro module already installed.', 'error');
      zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypaldp', 'NONSSL'));
      return 'failed';
    }
    // cannot install DP if EC not already enabled:
    if (!defined('MODULE_PAYMENT_PAYPALWPP_STATUS') || MODULE_PAYMENT_PAYPALWPP_STATUS != 'True') {
      $messageStack->add_session('<strong>Sorry, you must install and configure PayPal Express Checkout first.</strong> PayPal Website Payments Pro requires that you offer Express Checkout to your customers.<br /><a href="' . zen_href_link('modules.php?set=payment&module=paypalwpp', '', 'NONSSL') . '">Click here to set up Express Checkout.</a>' , 'error');
      zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypaldp', 'NONSSL'));
      return 'failed';
    }
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable this Payment Module', 'MODULE_PAYMENT_PAYPALDP_STATUS', 'True', 'Do you want to enable this payment module?', '6', '25', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Live or Sandbox', 'MODULE_PAYMENT_PAYPALDP_SERVER', 'live', '<strong>Live: </strong> Used to process Live transactions<br><strong>Sandbox: </strong>For developers and testing', '6', '25', 'zen_cfg_select_option(array(\'live\', \'sandbox\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_PAYPALDP_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PAYPALDP_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '25', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID', '2', 'Set the status of orders paid with this payment module to this value. <br /><strong>Recommended: Processing[2]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Unpaid Order Status', 'MODULE_PAYMENT_PAYPALDP_ORDER_PENDING_STATUS_ID', '1', 'Set the status of unpaid orders made with this payment module to this value. <br /><strong>Recommended: Pending[1]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Refund Order Status', 'MODULE_PAYMENT_PAYPALDP_REFUNDED_STATUS_ID', '1', 'Set the status of refunded orders to this value. <br /><strong>Recommended: Pending[1]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Payment Action', 'MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE', 'Final Sale', 'How do you want to obtain payment?<br /><strong>Default: Final Sale</strong>', '6', '25', 'zen_cfg_select_option(array(\'Auth Only\', \'Final Sale\'), ',  now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Currency', 'MODULE_PAYMENT_PAYPALDP_CURRENCY',  'Selected Currency', 'Which currency should the order be sent to PayPal as? <br />NOTE: if an unsupported currency is sent to PayPal, it will be auto-converted to USD (or GBP if using UK account)<br /><strong>Default: Selected Currency</strong>', '6', '25', 'zen_cfg_select_option(array(\'Selected Currency\', \'Only USD\', \'Only AUD\', \'Only CAD\', \'Only EUR\', \'Only GBP\', \'Only CHF\', \'Only CZK\', \'Only DKK\', \'Only HKD\', \'Only HUF\', \'Only JPY\', \'Only NOK\', \'Only NZD\', \'Only PLN\', \'Only SEK\', \'Only SGD\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Fraud Mgmt Filters - FMF', 'MODULE_PAYMENT_PAYPALDP_EC_RETURN_FMF_DETAILS', 'No', 'If you have enabled FMF support in your PayPal account and wish to utilize it in your transactions, set this to yes. Otherwise, leave it at No.', '6', '25','zen_cfg_select_option(array(\'No\', \'Yes\'), ', now())");

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Merchant Country', 'MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY', 'USA', 'Which country is your PayPal Account registered to? <br /><u>Choices:</u><br /><font color=green>You will need to supply <strong>API Settings</strong> in the Express Checkout module.</font><br /><strong>USA and Canada merchants</strong> need PayPal API credentials and a PayPal Payments Pro account.<br /><strong>UK merchants</strong> need to supply <strong>PAYFLOW settings</strong> (and have a Payflow account)', '6', '25',  'zen_cfg_select_option(array(\'USA\', \'UK\', \'Canada\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Debug Mode', 'MODULE_PAYMENT_PAYPALDP_DEBUGGING', 'Off', 'Would you like to enable debug mode?  A complete detailed log of failed transactions will be emailed to the store owner.', '6', '25', 'zen_cfg_select_option(array(\'Off\', \'Alerts Only\', \'Log File\', \'Log and Email\'), ', now())");

    // 3D-Secure
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cardinal Processor ID', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR', '134-01', 'The processor ID for the Cardinal Centinel service. ', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cardinal Merchant ID', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT', 'enter value', 'The merchant ID for the Cardinal Centinel service. ', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, set_function, use_function) values ('Cardinal Transaction Password', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD', '', 'Enter your Cardinal Transaction Password from your Cardinal Merchant Admin console. This is used to secure and verify that the transaction originated from your store legitimately.', '6', '25', now(), 'zen_cfg_password_input(', 'zen_cfg_password_display')");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Only Accept Chargeback-Protected Orders via Cardinal?', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ', 'No', 'Only proceed with authorization when the Cardinal authentication result provides chargeback protection? ', '6', '25', 'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");

    $this->notify('NOTIFY_PAYMENT_PAYPALDP_INSTALLED');
  }
1152156
def install_sql_hook():
    """"""
    try:
        from django.db.backends.utils import CursorWrapper
    except ImportError:
        from django.db.backends.util import CursorWrapper

    try:
        real_execute = CursorWrapper.execute
        real_executemany = CursorWrapper.executemany
    except AttributeError:
        # XXX(mitsuhiko): On some very old django versions (<1.6) this
        # trickery would have to look different but I can't be bothered.
        return

    def record_many_sql(vendor, alias, start, sql, param_list):
        duration = time.time() - start
        for params in param_list:
            record_sql(vendor, alias, start, duration, sql, params)

    def execute(self, sql, params=None):
        start = time.time()
        try:
            return real_execute(self, sql, params)
        finally:
            record_sql(self.db.vendor, getattr(self.db, 'alias', None),
                       start, time.time() - start, sql, params)

    def executemany(self, sql, param_list):
        start = time.time()
        try:
            return real_executemany(self, sql, param_list)
        finally:
            record_many_sql(self.db.vendor, getattr(self.db, 'alias', None),
                            start, sql, param_list)

    CursorWrapper.execute = execute
    CursorWrapper.executemany = executemany
    breadcrumbs.ignore_logger('django.db.backends')
354136
def database_add_tags(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/addTags' % object_id, input_params, always_retry=always_retry, **kwargs)
1183498
def manage_admins():
    """"""
    build = g.build

    # Do not show cached data
    db.session.add(build)
    db.session.refresh(build)

    add_form = forms.AddAdminForm()
    if add_form.validate_on_submit():

        invitation_user_id = '%s:%s' % (
            models.User.EMAIL_INVITATION, add_form.email_address.data)

        invitation_user = models.User.query.get(invitation_user_id)
        if not invitation_user:
            invitation_user = models.User(
                id=invitation_user_id,
                email_address=add_form.email_address.data)
            db.session.add(invitation_user)

        db.session.add(build)
        db.session.add(invitation_user)
        db.session.refresh(build, lockmode='update')

        build.owners.append(invitation_user)
        save_admin_log(build, invited_new_admin=True,
                       message=invitation_user.email_address)

        db.session.commit()

        logging.info('Added user=%r as owner to build_id=%r',
                     invitation_user.id, build.id)
        return redirect(url_for('manage_admins', build_id=build.id))

    add_form.build_id.data = build.id

    revoke_form_list = []
    for user in build.owners:
        form = forms.RemoveAdminForm()
        form.user_id.data = user.id
        form.build_id.data = build.id
        form.revoke.data = True
        revoke_form_list.append((user, form))

    return render_template(
        'view_admins.html',
        build=build,
        add_form=add_form,
        revoke_form_list=revoke_form_list)
1226989
function install() {
    global $db;
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('This module is installed', 'MODULE_ORDER_TOTAL_COUPON_STATUS', 'true', '', '6', '1','zen_cfg_select_option(array(\'true\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_ORDER_TOTAL_COUPON_SORT_ORDER', '280', 'Sort order of display.', '6', '2', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function ,date_added) values ('Include Shipping', 'MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING', 'true', 'Include Shipping in calculation', '6', '5', 'zen_cfg_select_option(array(\'true\', \'false\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function ,date_added) values ('Include Tax', 'MODULE_ORDER_TOTAL_COUPON_INC_TAX', 'false', 'Include Tax in calculation.', '6', '6','zen_cfg_select_option(array(\'true\', \'false\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function ,date_added) values ('Re-calculate Tax', 'MODULE_ORDER_TOTAL_COUPON_CALC_TAX', 'Standard', 'Re-Calculate Tax', '6', '7','zen_cfg_select_option(array(\'None\', \'Standard\', \'Credit Note\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_ORDER_TOTAL_COUPON_TAX_CLASS', '0', 'Use the following tax class when treating Discount Coupon as Credit Note.', '6', '0', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())");
  }
1180223
def upsert_module_file(module_ident, fileid, filename):
    
    with db_connect() as db_conn:
        with db_conn.cursor() as cursor:
            cursor.execute("SELECT true FROM module_files "
                           "WHERE module_ident = %s "
                           "AND filename = %s",
                           (module_ident, filename,))
            try:
                cursor.fetchone()[0]
            except (IndexError, TypeError):
                cursor.execute("INSERT INTO module_files "
                               "(module_ident, fileid, filename) "
                               "VALUES (%s, %s, %s)",
                               (module_ident, fileid, filename,))
            else:
                cursor.execute("UPDATE module_files "
                               "SET (fileid) = (%s) "
                               "WHERE module_ident = %s AND filename = %s",
                               (fileid, module_ident, filename,))
1296063
function install( $package, $installType, $parameters,
                      $name, $os, $filename, $subdirectory,
                      $content, &$installParameters,
                      &$installData )
    {
        $db = eZDB::instance();

        $siteAccess = $content->getAttribute( 'site-access' );
        if ( isset( $installParameters['site_access_map'] ) &&
             isset( $installParameters['site_access_map'][$siteAccess] ) )
        {
            $siteAccess = $installParameters['site_access_map'][$siteAccess];
        }

        $filename = $content->getAttribute( 'filename' );

        $ini = eZINI::instance( $filename, 'settings', null, null, true );
        $ini->prependOverrideDir( "siteaccess/$siteAccess", false, 'siteaccess' );
        $ini->loadCache();

        $blocks =& $content->elementByName( 'blocks' );
        $blockArray =& $blocks->getElementsByTagName( 'block' );

        foreach ( $blockArray as $block )
        {
            $blockname = $block->getAttribute( 'name' );

            $blockVariableArray = $block->getElementsByTagName( 'block-variable' );
            foreach( $blockVariableArray as $blockVariable )
            {
                $variableName = $blockVariable->getAttribute( 'name' );
                $variableValues = $blockVariable->getElementsByTagName( 'value' );

                if ( count( $variableValues ) == 1 )
                {
                    $value = eZINIAddonPackageHandler::currentID( $variableValues[0], $db );
                    $ini->setVariable( $blockname, $variableName, $value );
                }
                else
                {
                    $valueArray = array();
                    foreach( $variableValues as $variableNode )
                    {
                        $valueName = $variableNode->getAttribute( 'name' );
                        $value = eZINIAddonPackageHandler::currentID( $variableNode, $db );
                        $valueArray[$valueName] = $value;
                    }
                    $ini->setVariable( $blockname, $variableName, $valueArray );
                }
            }
        }

        $ini->save();

        return true;
    }
301396
function insert()
    {
        $item = array();
        $item['owner'] = arg('owner', 'int');
        $item['name'] = arg('name', '/[^a-z0-9_]/i');
        $item['title'] = arg('title', 'dbsafe');
        $item['caption'] = arg('caption', 'dbsafe');
        $item['description'] = arg('description', 'dbsafe');
        $item['hint'] = arg('hint', 'dbsafe');
        $item['keywords'] = arg('keywords', 'dbsafe');
        $item['template'] = arg('template', 'dbsafe');
        $item['type'] = arg('type', 'dbsafe');
        $item['active'] = arg('active', 'int');
        $item['visible'] = arg('visible', 'int');
        $item['access'] = arg('access', 'int');
        $item['position'] = arg('position', 'int');
        $item['options'] = arg('options');
        $item['created'] = $item['updated'] = gettime('Y-m-d H:i:s');

        $temp = Eresus_CMS::getLegacyKernel()->sections->get("(`name`='" . $item['name'] .
        "') AND (`owner`='" . $item['owner'] . "')");
        if (count($temp) == 0)
        {
            Eresus_CMS::getLegacyKernel()->sections->add($item);
            dbReorderItems('pages', "`owner`='".arg('owner', 'int')."'");
            HTTP::redirect(Eresus_Kernel::app()->getPage()->url(array('id'=>'')));
        }
        else
        {
            Eresus_Kernel::app()->getPage()->addErrorMessage(
                sprintf(errItemWithSameName, $item['name']));
            saveRequest();
            HTTP::redirect(Eresus_CMS::getLegacyKernel()->request['referer']);
        }
    }
1314210
def configure_db(self, hostname, database, username, admin=False):
        """"""
        self.connect(password=self.get_mysql_root_password())
        if not self.database_exists(database):
            self.create_database(database)

        remote_ip = self.normalize_address(hostname)
        password = self.get_mysql_password(username)
        if not self.grant_exists(database, username, remote_ip):
            if not admin:
                self.create_grant(database, username, remote_ip, password)
            else:
                self.create_admin_grant(username, remote_ip, password)
            self.flush_priviledges()

        return password
1085738
protected function addAdditionTables() : void
    {
        $dbms = strtoupper($this->db->getDBDriver());
        foreach (\constant("static::{$dbms}_ADDITIONAL_TABLES") as $table) {
            $this->tables[]['table_name'] = $table;
        }
    }
943742
def populate_db(sql_path):
    """"""

    logger.info("Populating DB %s from %s", repr(DB["NAME"]), repr(sql_path))
    shell(
        'psql -U "{USER}" -h "{HOST}" -d "{NAME}" --file={sql_path}'.format(
            sql_path=sql_path, **DB
        )
    )
344313
private static function setupModule()
    {
        // Check if ddmedia table was already created, if not create it.
        if (!self::tableExists('ddmedia')) {
            self::executeSQL(self::$_sCreateDdMediaSql);
        }
        // Check if ddmedia table has all needed fields, if not add them to the table.
        foreach (self::$_aSetupDdMediaSQLs as $sField => $sSql) {
            if (!self::fieldExists($sField, 'ddmedia')) {
                self::executeSQL($sSql);
            }
        }
        /** @var \OxidEsales\Eshop\Core\Config $oConfig */
        $oConfig = Registry::getConfig();
        $oConfig->saveShopConfVar('bool', 'blModuleWasEnabled', 'true', $oConfig->getShopId(), 'module:ddoewysiwyg');
    }