Same as {@link DB#withDb(DataSource, Supplier)}, but with db name {@link DB#DEFAULT_NAME}.
326659
public static <T> T withDb(DataSource dataSource, Supplier<T> supplier) {
        return new DB(DB.DEFAULT_NAME).withDb(dataSource, supplier);
    }
894601
function (DB_name, name, onDone, prefix) {

	//LOG.warn('init ' + DB_name + ' collection: ' + name, 'SR.DB');

	if (l_DBclient.hasOwnProperty(DB_name) === false) {
		LOG.error('DBclient not init or authenticated for DB [' + DB_name + ']', 'SR.DB');
		return UTIL.safeCall(onDone, false);
	}

	// check if already init
	if (l_getCollection(name, undefined, DB_name) !== undefined) {
		LOG.warn('DB [' + DB_name + '] collection [' + name + '] already loaded', 'SR.DB');
		LOG.warn('please check if different codes are using the same collection names', 'SR.DB');
		// NOTE: we assume double declaration of collection name is ok
		return UTIL.safeCall(onDone, true);
	}

	// build collection name to prefix with server name or a specified prefix
	var collection_name = (prefix || SR.Settings.SERVER_INFO.name) + ':' + name;

	// original simple version
	//var collection_name = name;

	l_DBclient[DB_name].collection(collection_name,
		function (err, collection) {
			if (err) {
				LOG.error(err, 'SR.DB');
				LOG.error('init DB [' + DB_name + ' ] collection [' + collection_name + '] error', 'SR.DB');
				UTIL.safeCall(onDone, false);
			} else {
				// store each name as a collection entry in collection object
				// collection name, instance(conn) , cache (idx by _id)
				var msg = 'init DB [' + DB_name + '] collection [' + collection_name + '] success';
				LOG.debug(msg, 'SR.DB');
				if (l_clts.hasOwnProperty(DB_name) === false) {
					l_clts[DB_name] = {};
				}

				// store collection instance into a two-level map
				l_clts[DB_name][name] = collection;

				// attach entity list to collection (for object caching)
				l_clts[DB_name][name].cache = {};

				UTIL.safeCall(onDone, true);
			}
		}
	);
}
525159
public void setDBPedia(String dbpedia) {
    if(dbpedia != null) {
      dbpedia = dbpedia.trim();
    }
    this.dbpedia = dbpedia;
  }
592803
public boolean setDataRecord(DataRecord dataRecord)
    {
        if (dataRecord.getHandle(DBConstants.DATA_SOURCE_HANDLE) == null)
        {   // No data source handle, mean you may need a table specified.
            String strObjectSource = (String)dataRecord.getHandle(DBConstants.OBJECT_SOURCE_HANDLE);
            if (strObjectSource != null)
            {
                int iLastColon = strObjectSource.lastIndexOf(BaseTable.HANDLE_SEPARATOR);
                if ((iLastColon > 0) && (iLastColon < strObjectSource.length() - 1))
                {
                    String strTableName = strObjectSource.substring(iLastColon + 1);
                    Iterator<BaseTable> iterator = this.getTables();
                    while (iterator.hasNext())
                    {
                        BaseTable table = iterator.next();
                        if (strTableName.equals(table.getRecord().getTableNames(false)))
                            this.setCurrentTable(table);
                    }
                }
            }
        }
        else if (dataRecord.getHandle(DBConstants.DATA_SOURCE_HANDLE) instanceof FullDataSource)
        {   // Always
            this.setCurrentTable(((FullDataSource)dataRecord.getHandle(DBConstants.DATA_SOURCE_HANDLE)).getTable());
        }
        boolean bSuccess = super.setDataRecord(dataRecord);
        this.syncCurrentToBase();
        return bSuccess;
    }
182161
public BatchFraction defaultJobRepository(final String name, final DatasourcesFraction datasource) {
        jdbcJobRepository(name, datasource);
        return defaultJobRepository(name);
    }
943667
@Override
	public JdbcDatabaseDescriptor dbByName(final String dbName) {
		Collection<H2DatabaseWorking> select = CollectionUtils.select(dbsw, new Predicate<H2DatabaseWorking>() {

			@Override
			public boolean evaluate(H2DatabaseWorking db) {
				return dbName.equals( db.getName() );
			}

		});
		if(CollectionUtils.size(select)==0){
			throw new IllegalArgumentException("There are no databases called '" + dbName + "'");
		}
		if(CollectionUtils.size(select)>=2){
			throw new IllegalArgumentException("More than one database is called '" + dbName + "'");
		}
		return CollectionUtils.extractSingleton( select );
	}
834376
private DBService createDefaultDBService() {
        m_logger.info("Creating DBService for default tenant");
        String dbServiceName = ServerParams.instance().getModuleParamString("DBService", "dbservice");
        if (Utils.isEmpty(dbServiceName)) {
            throw new RuntimeException("'DBService.dbservice' parameter is not defined.");
        }

        DBService dbservice = null;
        Tenant defaultTenant = TenantService.instance().getDefaultTenant();
        boolean bDBOpened = false;
        while (!bDBOpened) {
            try {
                // Find and call the constructor DBService(Tenant).
                @SuppressWarnings("unchecked")
                Class<DBService> serviceClass = (Class<DBService>) Class.forName(dbServiceName);
                Constructor<DBService> constructor = serviceClass.getConstructor(Tenant.class);
                dbservice = constructor.newInstance(defaultTenant);
                dbservice.initialize();
                dbservice.start();
                bDBOpened = true;
            } catch (IllegalArgumentException e) {
                throw new RuntimeException("Cannot load specified 'dbservice': " + dbServiceName, e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Could not load dbservice class '" + dbServiceName + "'", e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Required constructor missing for dbservice class: " + dbServiceName, e);
            } catch (SecurityException | InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Could not invoke constructor for dbservice class: " + dbServiceName, e);
            } catch (InvocationTargetException e) {
                // This is thrown when a constructor is invoked via reflection.
                if (!(e.getTargetException() instanceof DBNotAvailableException)) {
                    throw new RuntimeException("Could not invoke constructor for dbservice class: " + dbServiceName, e);
                }
            } catch (DBNotAvailableException e) {
                // Fall through to retry.
            } catch (Throwable e) {
                throw new RuntimeException("Failed to initialize default DBService: " + dbServiceName, e);
            }
            if (!bDBOpened) {
                m_logger.info("Database is not reachable. Waiting to retry");
                try {
                    Thread.sleep(db_connect_retry_wait_millis);
                } catch (InterruptedException ex2) {
                    // ignore
                }
            }
        }
        return dbservice;
        
    }
355878
public static <T> T withDb(String driver, String url, Properties properties, Supplier<T> supplier) {
        return new DB(DB.DEFAULT_NAME).withDb(driver, url, properties, supplier);
    }
773132
@Override
  public final void createDatabase(final String pDbName,
    final int pDbId) throws Exception {
    String dbNm = this.databasePrefix + pDbName + ".sqlite";
    synchronized (this.factoryAppBeans) {
      if (!this.factoryAppBeans.getDatabaseName().equals(dbNm)) {
        this.factoryAppBeans.setDatabaseName(dbNm);
        this.factoryAppBeans.setNewDatabaseId(pDbId);
        this.factoryAppBeans.handleDatabaseChanged();
      }
    }
  }
365195
private String getDatabaseProductName(WSDataSource dataSource) throws Exception {
        String dbProductName = dataSource.getDatabaseProductName();
        if (dbProductName == null) {
            // Query the metadata under a new transaction and commit right away
            LocalTransactionCurrent localTranCurrent = this.localTranCurrent;
            LocalTransactionCoordinator suspendedLTC = localTranCurrent.suspend();
            EmbeddableWebSphereTransactionManager tranMgr = this.tranMgr;
            Transaction suspendedTran = suspendedLTC == null ? tranMgr.suspend() : null;
            boolean tranStarted = false;
            try {
                tranMgr.begin();
                tranStarted = true;
                Connection con = dataSource.getConnection();
                try {
                    dbProductName = con.getMetaData().getDatabaseProductName();
                } finally {
                    con.close();
                }
            } finally {
                try {
                    if (tranStarted)
                        tranMgr.commit();
                } finally {
                    // resume
                    if (suspendedTran != null)
                        tranMgr.resume(suspendedTran);
                    else if (suspendedLTC != null)
                        localTranCurrent.resume(suspendedLTC);
                }
            }
        }
        return dbProductName;
    }
870056
public DBService getDefaultDB() {
        String defaultTenantName = TenantService.instance().getDefaultTenantName();
        synchronized (m_tenantDBMap) {
            DBService dbservice = m_tenantDBMap.get(defaultTenantName);
            assert dbservice != null : "Database for default tenant not found";
            return dbservice;
        }
    }
939207
public static SqlConfig getConfig(final String dataSourceName) {
		DataSourceConnectionSupplierImpl connectionSupplier = new DataSourceConnectionSupplierImpl(dataSourceName);
		return new DefaultSqlConfig(connectionSupplier, null);
	}
479654
protected final <T> T createDataSource(Class<T> dataSourceClass) throws SQLException {
		if (getRealDataSourceClassName() == null) {
			throw new SQLException("Property realDataSourceClassName is not set");
		}
		try {
			T ds = dataSourceClass.cast(Class.forName(realDataSourceClassName).newInstance());
			for (Method m : ds.getClass().getMethods()) {
				String methodName = m.getName();
				if (methodName.startsWith("set") && m.getParameterTypes().length == 1) {
					final Object propertyValue;
					if (methodName.equals("setUser")) {
						propertyValue = getUser();
					} else if (methodName.equals("setPassword")) {
						propertyValue = getPassword();
					} else if (methodName.equalsIgnoreCase("setUrl")) {
						propertyValue = getRealUrl();
					} else if (methodName.equals("setLogWriter")) {
						propertyValue = getLogWriter();
					} else if (methodName.equals("setLoginTimeout")) {
						propertyValue = getLoginTimeout();
					} else {
						String propertyName = methodName.substring(3, 4).toLowerCase();
						if (methodName.length() > 4) {
							propertyName += methodName.substring(4);
						}
						final Class<?> propertyType = m.getParameterTypes()[0];
						propertyValue = getPropertyAs(propertyName, propertyType);
					}
					if (propertyValue != null) {
						m.invoke(ds, propertyValue);
					}
				}
			}
			return ds;

		} catch (Exception e) {
			throw new SQLException(e);
		}
	}
838175
@Override
    public SqlInfo buildSqlInfo(BuildSource source) {
        Object paramObj = source.getParamObj();
        SqlInfo sqlInfo = source.getSqlInfo();
        Node node = source.getNode();

        // 循环判断所有`when`的值，直到能找到第n个when的时候，如果都为false，则跳出循环走else的逻辑
        // 循环过程中，如果判断到第x个when解析后的值为true时，则解析拼接这第x个then的值到Sql中，并直接返回.
        int i = 0;
        while (true) {
            // 每次循环加1，如果是第一个，则，when/then等添加的后缀为空字符串.
            i++;
            String x = i == 1 ? "" : String.valueOf(i);

            // 获取第i个when属性的文本值，如果其文本内容为空则不再拼接，进入else的分支条件来拼接Sql片段信息.
            String whenText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_WHEN + x);
            if (StringHelper.isBlank(whenText)) {
                log.info("case标签中第" + i + "个when属性不存在或者内容为空，进入else的分支条件.");
                break;
            }

            // 如果when属性的解析值为true,则拼接其对应的`then`块的SQL片段.then块的值为解析其字符串模板的值.
            if (ParseHelper.isTrue(whenText, paramObj)) {
                String thenText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_THEN + x);
                if (StringHelper.isNotBlank(thenText)) {
                    sqlInfo.getJoin().append(ParseHelper.parseTemplate(thenText, paramObj));
                }
                return sqlInfo;
            }
        }

        // 如果没进入前面任何一个when-then的分支块，则进入else的分支，如果else为空，则直接返回原SqlInfo.
        String elseText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_ELSE);
        if (StringHelper.isBlank(elseText)) {
            log.info("case标签中else属性不存在或者内容为空，不拼接任何SQL片段.");
            return sqlInfo;
        }

        sqlInfo.getJoin().append(ParseHelper.parseTemplate(elseText, paramObj));
        return sqlInfo;
    }
969711
public void init(DatabaseOwner databaseOwner, String strDbName, int iDatabaseType, Map<String, Object> properties)
    {
        super.init(databaseOwner, strDbName, iDatabaseType, properties);

        this.setProperty(DBConstants.READ_ONLY_DB, DBConstants.TRUE);   // This is always read-only
    }
181732
String getDatabaseName(String dbName) {
        if (mFileNameMap == null) {
            return null;
        }
        String name = mFileNameMap.get(dbName);
        if (name == null && dbName != null) {
            name = mFileNameMap.get(null);
        }
        if (name == null) {
            return null;
        }
        if (mDatabaseHook != null) {
            try {
                dbName = mDatabaseHook.databaseName(dbName);
            } catch (IncompatibleClassChangeError e) {
                // Method not implemented.
            }
        }
        return dbName;
    }
518936
@Override
	public HsqlDatabaseDescriptor dbByName(final String dbName) {
		Collection<HsqlDatabaseDescriptor> select = CollectionUtils.select(dbs,
				new Predicate<HsqlDatabaseDescriptor>() {

					@Override
					public boolean evaluate(HsqlDatabaseDescriptor db) {
						return dbName.equals(db.getDbName());
					}

				});
		if (CollectionUtils.size(select) == 0) {
			throw new IllegalArgumentException(
					"There are no databases called '" + dbName + "'");
		}
		if (CollectionUtils.size(select) >= 2) {
			throw new IllegalArgumentException(
					"More than one database is called '" + dbName + "'");
		}
		return CollectionUtils.extractSingleton(select);
	}