proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/common/util/SortedProperties.java
|
SortedProperties
|
store
|
class SortedProperties extends Properties {
private static final long serialVersionUID = 1L;
@Override
public synchronized Enumeration<Object> keys() {
Vector<String> v = new Vector<String>();
for (Object o : keySet()) {
v.add(o.toString());
}
Collections.sort(v);
return new Vector<Object>(v).elements();
}
/**
* Load a properties object from a file.
*
* @param fileName the name of the properties file
* @return the properties object
*/
public static synchronized SortedProperties loadProperties(String fileName) throws IOException {
SortedProperties prop = new SortedProperties();
if (FileUtils.exists(fileName)) {
InputStream in = null;
try {
in = FileUtils.newInputStream(fileName);
prop.load(in);
} finally {
if (in != null) {
in.close();
}
}
}
return prop;
}
/**
* Store a properties file. The header and the date is not written.
*
* @param fileName the target file name
*/
public synchronized void store(String fileName) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Convert the map to a list of line in the form key=value.
*
* @return the lines
*/
public synchronized String toLines() {
StringBuilder buff = new StringBuilder();
for (Entry<Object, Object> e : new TreeMap<Object, Object>(this).entrySet()) {
buff.append(e.getKey()).append('=').append(e.getValue()).append('\n');
}
return buff.toString();
}
/**
* Convert a String to a map.
*
* @param s the string
* @return the map
*/
public static SortedProperties fromLines(String s) {
SortedProperties p = new SortedProperties();
for (String line : StringUtils.arraySplit(s, '\n')) {
int idx = line.indexOf('=');
if (idx > 0) {
p.put(line.substring(0, idx), line.substring(idx + 1));
}
}
return p;
}
}
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
store(out, null);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
InputStreamReader reader = new InputStreamReader(in, "ISO8859-1");
LineNumberReader r = new LineNumberReader(reader);
Writer w;
try {
w = new OutputStreamWriter(FileUtils.newOutputStream(fileName, false));
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
PrintWriter writer = new PrintWriter(new BufferedWriter(w));
while (true) {
String line = r.readLine();
if (line == null) {
break;
}
if (!line.startsWith("#")) {
writer.print(line + "\n");
}
}
writer.close();
| 589
| 218
| 807
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(java.util.Properties) ,public synchronized void clear() ,public synchronized java.lang.Object clone() ,public synchronized java.lang.Object compute(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfAbsent(java.lang.Object, Function<? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfPresent(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<java.lang.Object> elements() ,public Set<Entry<java.lang.Object,java.lang.Object>> entrySet() ,public synchronized boolean equals(java.lang.Object) ,public synchronized void forEach(BiConsumer<? super java.lang.Object,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public java.lang.String getProperty(java.lang.String) ,public java.lang.String getProperty(java.lang.String, java.lang.String) ,public synchronized int hashCode() ,public boolean isEmpty() ,public Set<java.lang.Object> keySet() ,public Enumeration<java.lang.Object> keys() ,public void list(java.io.PrintStream) ,public void list(java.io.PrintWriter) ,public synchronized void load(java.io.Reader) throws java.io.IOException,public synchronized void load(java.io.InputStream) throws java.io.IOException,public synchronized void loadFromXML(java.io.InputStream) throws java.io.IOException, java.util.InvalidPropertiesFormatException,public synchronized java.lang.Object merge(java.lang.Object, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public Enumeration<?> propertyNames() ,public synchronized java.lang.Object put(java.lang.Object, java.lang.Object) ,public synchronized void putAll(Map<?,?>) ,public synchronized java.lang.Object putIfAbsent(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object remove(java.lang.Object) ,public synchronized boolean remove(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object replace(java.lang.Object, java.lang.Object) ,public synchronized boolean replace(java.lang.Object, java.lang.Object, java.lang.Object) ,public synchronized void replaceAll(BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public void save(java.io.OutputStream, java.lang.String) ,public synchronized java.lang.Object setProperty(java.lang.String, java.lang.String) ,public int size() ,public void store(java.io.Writer, java.lang.String) throws java.io.IOException,public void store(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.nio.charset.Charset) throws java.io.IOException,public Set<java.lang.String> stringPropertyNames() ,public synchronized java.lang.String toString() ,public Collection<java.lang.Object> values() <variables>private static final jdk.internal.misc.Unsafe UNSAFE,protected volatile java.util.Properties defaults,private volatile transient ConcurrentHashMap<java.lang.Object,java.lang.Object> map,private static final long serialVersionUID
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/common/util/StatementBuilder.java
|
StatementBuilder
|
appendOnlyFirst
|
class StatementBuilder {
private final StringBuilder builder = new StringBuilder();
private int index;
/**
* Create a new builder.
*/
public StatementBuilder() {
// nothing to do
}
/**
* Create a new builder.
*
* @param string the initial string
*/
public StatementBuilder(String string) {
builder.append(string);
}
/**
* Append a text.
*
* @param s the text to append
* @return itself
*/
public StatementBuilder append(String s) {
builder.append(s);
return this;
}
/**
* Append a character.
*
* @param c the character to append
* @return itself
*/
public StatementBuilder append(char c) {
builder.append(c);
return this;
}
/**
* Append a number.
*
* @param x the number to append
* @return itself
*/
public StatementBuilder append(long x) {
builder.append(x);
return this;
}
/**
* Reset the loop counter.
*
* @return itself
*/
public StatementBuilder resetCount() {
index = 0;
return this;
}
/**
* Append a text, but only if appendExceptFirst was never called.
*
* @param s the text to append
*/
public StatementBuilder appendOnlyFirst(String s) {<FILL_FUNCTION_BODY>}
/**
* Append a text, except when this method is called the first time.
*
* @param s the text to append
*/
public StatementBuilder appendExceptFirst(String s) {
if (index++ > 0) {
builder.append(s);
}
return this;
}
@Override
public String toString() {
return builder.toString();
}
/**
* Get the length.
*
* @return the length
*/
public int length() {
return builder.length();
}
}
|
if (index == 0) {
builder.append(s);
}
return this;
| 556
| 28
| 584
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/common/util/Task.java
|
Task
|
getException
|
class Task implements Runnable {
/**
* A flag indicating the get() method has been called.
*/
protected volatile boolean stop;
/**
* The result, if any.
*/
protected Object result;
private Thread thread;
private Exception ex;
/**
* The method to be implemented.
*
* @throws Exception any exception is wrapped in a RuntimeException
*/
public abstract void call() throws Exception;
@Override
public void run() {
try {
call();
} catch (Exception e) {
this.ex = e;
}
}
/**
* Start the thread.
*
* @return this
*/
public Task execute() {
return execute(getClass().getName());
}
/**
* Start the thread.
*
* @param threadName the name of the thread
* @return this
*/
public Task execute(String threadName) {
thread = new Thread(this, threadName);
thread.setDaemon(true);
thread.start();
return this;
}
/**
* Calling this method will set the stop flag and wait until the thread is
* stopped.
*
* @return the result, or null
* @throws RuntimeException if an exception in the method call occurs
*/
public Object get() {
Exception e = getException();
if (e != null) {
throw new RuntimeException(e);
}
return result;
}
/**
* Get the exception that was thrown in the call (if any).
*
* @return the exception or null
*/
public Exception getException() {<FILL_FUNCTION_BODY>}
}
|
stop = true;
if (thread == null) {
throw new IllegalStateException("Thread not started");
}
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
if (ex != null) {
return ex;
}
return null;
| 444
| 84
| 528
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/common/util/TempFileDeleter.java
|
TempFileDeleter
|
deleteUnused
|
class TempFileDeleter {
private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
private final HashMap<PhantomReference<?>, String> refMap = new HashMap<>();
private TempFileDeleter() {
// utility class
}
public static TempFileDeleter getInstance() {
return new TempFileDeleter();
}
/**
* Add a file to the list of temp files to delete. The file is deleted once
* the file object is garbage collected.
*
* @param fileName the file name
* @param file the object to monitor
* @return the reference that can be used to stop deleting the file
*/
public synchronized Reference<?> addFile(String fileName, Object file) {
IOUtils.trace("TempFileDeleter.addFile", fileName, file);
PhantomReference<?> ref = new PhantomReference<Object>(file, queue);
refMap.put(ref, fileName);
deleteUnused();
return ref;
}
/**
* Delete the given file now. This will remove the reference from the list.
*
* @param ref the reference as returned by addFile
* @param fileName the file name
*/
public synchronized void deleteFile(Reference<?> ref, String fileName) {
if (ref != null) {
String f2 = refMap.remove(ref);
if (f2 != null) {
if (SysProperties.CHECK) {
if (fileName != null && !f2.equals(fileName)) {
DbException.throwInternalError("f2:" + f2 + " f:" + fileName);
}
}
fileName = f2;
}
}
if (fileName != null && FileUtils.exists(fileName)) {
try {
IOUtils.trace("TempFileDeleter.deleteFile", fileName, null);
FileUtils.tryDelete(fileName);
} catch (Exception e) {
// TODO log such errors?
}
}
}
/**
* Delete all registered temp files.
*/
public void deleteAll() {
for (String tempFile : new ArrayList<>(refMap.values())) {
deleteFile(null, tempFile);
}
deleteUnused();
}
/**
* Delete all unused files now.
*/
public void deleteUnused() {<FILL_FUNCTION_BODY>}
/**
* This method is called if a file should no longer be deleted if the object
* is garbage collected.
*
* @param ref the reference as returned by addFile
* @param fileName the file name
*/
public void stopAutoDelete(Reference<?> ref, String fileName) {
IOUtils.trace("TempFileDeleter.stopAutoDelete", fileName, ref);
if (ref != null) {
String f2 = refMap.remove(ref);
if (SysProperties.CHECK) {
if (f2 == null || !f2.equals(fileName)) {
DbException.throwInternalError(
"f2:" + f2 + " " + (f2 == null ? "" : f2) + " f:" + fileName);
}
}
}
deleteUnused();
}
}
|
while (queue != null) {
Reference<? extends Object> ref = queue.poll();
if (ref == null) {
break;
}
deleteFile(ref, null);
}
| 839
| 56
| 895
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/LocalDataHandler.java
|
LocalDataHandler
|
getLobStorage
|
class LocalDataHandler implements DataHandler {
private final String cipher;
private final byte[] fileEncryptionKey;
private LobReader lobReader;
private LobStorage lobStorage;
public LocalDataHandler() {
this(null);
}
public LocalDataHandler(String cipher) {
this.cipher = cipher;
fileEncryptionKey = cipher == null ? null : MathUtils.secureRandomBytes(32);
}
public void setLobReader(LobReader lobReader) {
this.lobReader = lobReader;
}
@Override
public String getDatabasePath() {
return "";
}
@Override
public FileStorage openFile(String name, String mode, boolean mustExist) {
if (mustExist && !FileUtils.exists(name)) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name);
}
FileStorage fileStorage = FileStorage.open(this, name, mode, cipher, fileEncryptionKey);
fileStorage.setCheckedWriting(false);
return fileStorage;
}
@Override
public TempFileDeleter getTempFileDeleter() {
return TempFileDeleter.getInstance();
}
@Override
public void checkPowerOff() {
// ok
}
@Override
public void checkWritingAllowed() {
// ok
}
@Override
public int getMaxLengthInplaceLob() {
return SysProperties.LOB_CLIENT_MAX_SIZE_MEMORY;
}
@Override
public String getLobCompressionAlgorithm(int type) {
return null;
}
@Override
public LobStorage getLobStorage() {<FILL_FUNCTION_BODY>}
}
|
if (lobStorage == null) {
lobStorage = new LobLocalStorage(this, lobReader);
}
return lobStorage;
| 461
| 39
| 500
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/MemoryManager.java
|
MemoryManager
|
getFullGcThreshold
|
class MemoryManager {
private static final MemoryManager globalMemoryManager = new MemoryManager(getGlobalMaxMemory());
private static final long fullGcThreshold = getFullGcThreshold();
public static boolean needFullGc() {
return globalMemoryManager.getUsedMemory() > fullGcThreshold;
}
private static long getFullGcThreshold() {<FILL_FUNCTION_BODY>}
private static long getGlobalMaxMemory() {
MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
return mu.getMax();
}
public static MemoryManager getGlobalMemoryManager() {
return globalMemoryManager;
}
public static interface MemoryListener {
void wakeUp();
}
private static MemoryListener globalMemoryListener;
public static void setGlobalMemoryListener(MemoryListener globalMemoryListener) {
MemoryManager.globalMemoryListener = globalMemoryListener;
}
public static void wakeUpGlobalMemoryListener() {
if (globalMemoryListener != null)
globalMemoryListener.wakeUp();
}
private final AtomicLong usedMemory = new AtomicLong(0);
private long gcThreshold;
private boolean forceGc;
public MemoryManager(long maxMemory) {
setMaxMemory(maxMemory);
}
public void setMaxMemory(long maxMemory) {
if (maxMemory <= 0)
maxMemory = getGlobalMaxMemory();
gcThreshold = maxMemory / 2; // 占用内存超过一半时就可以触发GC
}
public long getMaxMemory() {
return gcThreshold * 2;
}
public long getUsedMemory() {
return usedMemory.get();
}
public void addUsedMemory(long delta) { // 正负都有可能
usedMemory.addAndGet(delta);
}
public boolean needGc() {
if (forceGc)
return true;
if (usedMemory.get() > gcThreshold)
return true;
// 看看全部使用的内存是否超过阈值
if (this != globalMemoryManager && globalMemoryManager.needGc())
return true;
return false;
}
public void forceGc(boolean b) {
forceGc = b;
}
}
|
long max = getGlobalMaxMemory();
long gcThreshold = max / 10 * 6;
// 小于512M时把阈值调低一些
if (max < 512 * 1024 * 1024)
gcThreshold = max / 10 * 3;
return SystemPropertyUtils.getLong("lealone.memory.fullGcThreshold", gcThreshold);
| 588
| 112
| 700
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/PluginBase.java
|
PluginBase
|
init
|
class PluginBase implements Plugin {
protected String name;
protected Map<String, String> config;
protected State state = State.NONE;
public PluginBase() {
}
public PluginBase(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Map<String, String> getConfig() {
return config;
}
@Override
public boolean isInited() {
return state != State.NONE;
}
@Override
public boolean isStarted() {
return state == State.STARTED;
}
@Override
public boolean isStopped() {
return state == State.STOPPED;
}
@Override
public synchronized void init(Map<String, String> config) {<FILL_FUNCTION_BODY>}
@Override
public synchronized void close() {
Class<Plugin> pluginClass = getPluginClass0();
Plugin p = PluginManager.getPlugin(pluginClass, getName());
if (p != null)
PluginManager.deregister(pluginClass, p);
state = State.NONE;
}
@Override
public void start() {
state = State.STARTED;
}
@Override
public void stop() {
state = State.STOPPED;
}
@Override
public State getState() {
return state;
}
@SuppressWarnings("unchecked")
private Class<Plugin> getPluginClass0() {
return (Class<Plugin>) getPluginClass();
}
public Class<? extends Plugin> getPluginClass() {
return Plugin.class;
}
}
|
if (!isInited()) {
this.config = config;
String pluginName = MapUtils.getString(config, "plugin_name", null);
if (pluginName != null)
setName(pluginName); // 使用create plugin创建插件对象时用命令指定的名称覆盖默认值
Class<Plugin> pluginClass = getPluginClass0();
PluginManager.register(pluginClass, this);
state = State.INITED;
}
| 485
| 120
| 605
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/PluginManager.java
|
PluginManager
|
getPlugin
|
class PluginManager<T extends Plugin> {
private static final Logger logger = LoggerFactory.getLogger(PluginManager.class);
private final Class<T> pluginClass;
private final Map<String, T> plugins = new ConcurrentHashMap<>();
private volatile boolean loaded = false;
protected PluginManager(Class<T> pluginClass) {
this.pluginClass = pluginClass;
}
public T getPlugin(String name) {<FILL_FUNCTION_BODY>}
public Collection<T> getPlugins() {
return plugins.values();
}
public void registerPlugin(T plugin, String... alias) {
plugins.put(plugin.getName().toUpperCase(), plugin);
// plugins.put(plugin.getClass().getName().toUpperCase(), plugin);
if (alias != null && alias.length > 0) {
for (String a : alias)
plugins.put(a.toUpperCase(), plugin);
}
}
public void deregisterPlugin(T plugin, String... alias) {
plugins.remove(plugin.getName().toUpperCase());
// plugins.remove(plugin.getClass().getName().toUpperCase());
if (alias != null && alias.length > 0) {
for (String a : alias)
plugins.remove(a.toUpperCase());
}
if (plugins.isEmpty())
loaded = false; // 可以重新加载
}
private synchronized void loadPlugins() {
if (loaded)
return;
Iterator<T> iterator = ServiceLoader.load(pluginClass).iterator();
while (iterator.hasNext()) {
try {
// 执行next时ServiceLoader内部会自动为每一个实现Plugin接口的类生成一个新实例
// 所以Plugin接口的实现类必需有一个public的无参数构造函数
T p = iterator.next();
registerPlugin(p);
} catch (Throwable t) {
// 只是发出警告
logger.warn("Failed to load plugin: " + pluginClass.getName(), t);
}
}
// 注意在load完之后再设为true,否则其他线程可能会因为不用等待load完成从而得到一个NPE
loaded = true;
}
private static final Map<Class<?>, PluginManager<?>> instances = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
private static <P extends Plugin> PluginManager<P> getInstance(P plugin) {
return (PluginManager<P>) getInstance(plugin.getClass());
}
@SuppressWarnings("unchecked")
private static <P extends Plugin> PluginManager<P> getInstance(Class<P> pluginClass) {
PluginManager<?> instance = instances.get(pluginClass);
if (instance == null) {
instance = new PluginManager<>(pluginClass);
PluginManager<?> old = instances.putIfAbsent(pluginClass, instance);
if (old != null) {
instance = old;
}
}
return (PluginManager<P>) instance;
}
public static <P extends Plugin> P getPlugin(Class<P> pluginClass, String name) {
return getInstance(pluginClass).getPlugin(name);
}
public static <P extends Plugin> Collection<P> getPlugins(Class<P> pluginClass) {
return getInstance(pluginClass).getPlugins();
}
public static <P extends Plugin> void register(P plugin, String... alias) {
getInstance(plugin).registerPlugin(plugin, alias);
}
public static <P extends Plugin> void register(Class<P> pluginClass, P plugin, String... alias) {
getInstance(pluginClass).registerPlugin(plugin, alias);
}
public static <P extends Plugin> void deregister(P plugin, String... alias) {
getInstance(plugin).deregisterPlugin(plugin, alias);
}
public static <P extends Plugin> void deregister(Class<P> pluginClass, P plugin, String... alias) {
getInstance(pluginClass).deregisterPlugin(plugin, alias);
}
}
|
if (name == null)
throw new NullPointerException("name is null");
if (!loaded)
loadPlugins();
return plugins.get(name.toUpperCase());
| 1,060
| 50
| 1,110
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/async/AsyncCallback.java
|
AsyncCallback
|
handleTimeout
|
class AsyncCallback<T> implements Future<T> {
public AsyncCallback() {
}
public void setDbException(DbException e, boolean cancel) {
}
public void run(NetInputStream in) {
}
protected void runInternal(NetInputStream in) throws Exception {
}
protected abstract T await(long timeoutMillis);
@Override
public T get() {
long timeoutMillis = networkTimeout > 0 ? networkTimeout : -1;
return await(timeoutMillis);
}
@Override
public T get(long timeoutMillis) {
return await(timeoutMillis);
}
@Override
public Future<T> onSuccess(AsyncHandler<T> handler) {
return this;
}
@Override
public Future<T> onFailure(AsyncHandler<Throwable> handler) {
return this;
}
@Override
public Future<T> onComplete(AsyncHandler<AsyncResult<T>> handler) {
return this;
}
public void setAsyncResult(Throwable cause) {
setAsyncResult(new AsyncResult<>(cause));
}
public void setAsyncResult(T result) {
setAsyncResult(new AsyncResult<>(result));
}
public void setAsyncResult(AsyncResult<T> asyncResult) {
}
private Packet packet;
private long startTime;
private int networkTimeout;
public void setPacket(Packet packet) {
this.packet = packet;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public int getNetworkTimeout() {
return networkTimeout;
}
public void setNetworkTimeout(int networkTimeout) {
this.networkTimeout = networkTimeout;
}
public void checkTimeout(long currentTime) {
if (networkTimeout <= 0 || startTime <= 0 || startTime + networkTimeout > currentTime)
return;
handleTimeout();
}
protected void handleTimeout() {<FILL_FUNCTION_BODY>}
public static <T> AsyncCallback<T> createSingleThreadCallback() {
return new SingleThreadAsyncCallback<>();
}
public static <T> AsyncCallback<T> createConcurrentCallback() {
return new ConcurrentAsyncCallback<>();
}
public static <T> AsyncCallback<T> create(boolean isSingleThread) {
return isSingleThread ? createSingleThreadCallback() : createConcurrentCallback();
}
}
|
String msg = "ack timeout, request start time: " + new java.sql.Timestamp(startTime) //
+ ", network timeout: " + networkTimeout + "ms" //
+ ", request packet: " + packet;
DbException e = DbException.get(ErrorCode.NETWORK_TIMEOUT_1, msg);
setAsyncResult(e);
networkTimeout = 0;
| 662
| 98
| 760
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/async/AsyncPeriodicTask.java
|
AsyncPeriodicTask
|
run
|
class AsyncPeriodicTask extends LinkableBase<AsyncPeriodicTask> implements AsyncTask {
private final long delay;
private Runnable runnable;
private long last;
private boolean canceled;
public AsyncPeriodicTask(long delay, Runnable runnable) {
this(delay, delay, runnable);
}
public AsyncPeriodicTask(long initialDelay, long delay, Runnable runnable) {
this.delay = delay;
this.runnable = runnable;
if (initialDelay > 0) {
last = System.currentTimeMillis() + initialDelay;
} else {
last = System.currentTimeMillis() + delay;
}
}
@Override
public boolean isPeriodic() {
return true;
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
public void cancel() {
canceled = true;
}
public boolean isCancelled() {
return canceled;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
public long getDelay() {
return delay;
}
public void setRunnable(Runnable runnable) {
this.runnable = runnable;
}
public void resetLast() {
last = 0;
}
}
|
if (canceled)
return;
long now = System.currentTimeMillis();
if (now > last) {
last = now + delay;
runnable.run();
}
| 365
| 54
| 419
|
<methods>public non-sealed void <init>() ,public com.lealone.db.async.AsyncPeriodicTask getNext() ,public void setNext(com.lealone.db.async.AsyncPeriodicTask) <variables>public com.lealone.db.async.AsyncPeriodicTask next
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/async/AsyncResult.java
|
AsyncResult
|
setResult
|
class AsyncResult<T> {
protected T result;
protected Throwable cause;
protected boolean succeeded;
protected boolean failed;
public AsyncResult() {
}
public AsyncResult(T result) {
setResult(result);
}
public AsyncResult(Throwable cause) {
setCause(cause);
}
public T getResult() {
return result;
}
public void setResult(T result) {<FILL_FUNCTION_BODY>}
public Throwable getCause() {
return cause;
}
public void setCause(Throwable cause) {
this.cause = cause;
failed = true;
succeeded = false;
}
public boolean isSucceeded() {
return succeeded;
}
public void setSucceeded(boolean succeeded) {
this.succeeded = succeeded;
}
public boolean isFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
}
|
this.result = result;
failed = false;
succeeded = true;
| 283
| 23
| 306
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/async/ConcurrentAsyncCallback.java
|
LatchObject
|
await
|
class LatchObject {
final CountDownLatch latch;
public LatchObject(CountDownLatch latch) {
this.latch = latch;
}
}
public ConcurrentAsyncCallback() {
}
@Override
public void setDbException(DbException e, boolean cancel) {
setAsyncResult(e);
if (cancel)
countDown();
}
@Override
public final void run(NetInputStream in) {
// 放在最前面,不能放在最后面,
// 否则调用了countDown,但是在设置runEnd为true前,调用await的线程读到的是false就会抛异常
runEnd = true;
// if (asyncResult == null) {
try {
runInternal(in);
} catch (Throwable t) {
setAsyncResult(t);
}
// }
}
@Override
protected T await(long timeoutMillis) {<FILL_FUNCTION_BODY>
|
Scheduler scheduler = SchedulerThread.currentScheduler();
if (scheduler != null)
scheduler.executeNextStatement();
if (latchObjectRef.compareAndSet(null, new LatchObject(new CountDownLatch(1)))) {
CountDownLatch latch = latchObjectRef.get().latch;
try {
if (timeoutMillis > 0)
latch.await(timeoutMillis, TimeUnit.MILLISECONDS);
else
latch.await();
if (asyncResult != null && asyncResult.isFailed())
throw DbException.convert(asyncResult.getCause());
// 如果没有执行过run,抛出合适的异常
if (!runEnd) {
handleTimeout();
}
} catch (InterruptedException e) {
throw DbException.convert(e);
}
if (asyncResult != null)
return asyncResult.getResult();
else
return null;
} else {
if (asyncResult.isFailed())
throw DbException.convert(asyncResult.getCause());
else
return asyncResult.getResult();
}
| 252
| 296
| 548
|
<methods>public void <init>() ,public void checkTimeout(long) ,public static AsyncCallback<T> create(boolean) ,public static AsyncCallback<T> createConcurrentCallback() ,public static AsyncCallback<T> createSingleThreadCallback() ,public T get() ,public T get(long) ,public int getNetworkTimeout() ,public long getStartTime() ,public Future<T> onComplete(AsyncHandler<AsyncResult<T>>) ,public Future<T> onFailure(AsyncHandler<java.lang.Throwable>) ,public Future<T> onSuccess(AsyncHandler<T>) ,public void run(com.lealone.net.NetInputStream) ,public void setAsyncResult(java.lang.Throwable) ,public void setAsyncResult(T) ,public void setAsyncResult(AsyncResult<T>) ,public void setDbException(com.lealone.common.exceptions.DbException, boolean) ,public void setNetworkTimeout(int) ,public void setPacket(com.lealone.server.protocol.Packet) ,public void setStartTime(long) <variables>private int networkTimeout,private com.lealone.server.protocol.Packet packet,private long startTime
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/async/SingleThreadAsyncCallback.java
|
SingleThreadAsyncCallback
|
await
|
class SingleThreadAsyncCallback<T> extends AsyncCallback<T> {
private AsyncHandler<AsyncResult<T>> completeHandler;
private AsyncHandler<T> successHandler;
private AsyncHandler<Throwable> failureHandler;
private AsyncResult<T> asyncResult;
public SingleThreadAsyncCallback() {
}
@Override
public void setDbException(DbException e, boolean cancel) {
setAsyncResult(e);
}
@Override
public void run(NetInputStream in) {
try {
runInternal(in);
} catch (Throwable t) {
setAsyncResult(t);
}
}
@Override
protected T await(long timeoutMillis) {<FILL_FUNCTION_BODY>}
@Override
public Future<T> onSuccess(AsyncHandler<T> handler) {
successHandler = handler;
if (asyncResult != null && asyncResult.isSucceeded()) {
handler.handle(asyncResult.getResult());
}
return this;
}
@Override
public Future<T> onFailure(AsyncHandler<Throwable> handler) {
failureHandler = handler;
if (asyncResult != null && asyncResult.isFailed()) {
handler.handle(asyncResult.getCause());
}
return this;
}
@Override
public Future<T> onComplete(AsyncHandler<AsyncResult<T>> handler) {
completeHandler = handler;
if (asyncResult != null) {
handler.handle(asyncResult);
}
return this;
}
@Override
public void setAsyncResult(AsyncResult<T> asyncResult) {
this.asyncResult = asyncResult;
if (completeHandler != null)
completeHandler.handle(asyncResult);
if (successHandler != null && asyncResult != null && asyncResult.isSucceeded())
successHandler.handle(asyncResult.getResult());
if (failureHandler != null && asyncResult != null && asyncResult.isFailed())
failureHandler.handle(asyncResult.getCause());
}
}
|
Scheduler scheduler = SchedulerThread.currentScheduler();
if (scheduler != null) {
scheduler.executeNextStatement();
// 如果被锁住了,需要重试
if (asyncResult == null) {
while (asyncResult == null) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
scheduler.executeNextStatement();
}
}
if (asyncResult.isSucceeded())
return asyncResult.getResult();
else
throw DbException.convert(asyncResult.getCause());
} else {
throw DbException.getInternalError();
}
| 538
| 176
| 714
|
<methods>public void <init>() ,public void checkTimeout(long) ,public static AsyncCallback<T> create(boolean) ,public static AsyncCallback<T> createConcurrentCallback() ,public static AsyncCallback<T> createSingleThreadCallback() ,public T get() ,public T get(long) ,public int getNetworkTimeout() ,public long getStartTime() ,public Future<T> onComplete(AsyncHandler<AsyncResult<T>>) ,public Future<T> onFailure(AsyncHandler<java.lang.Throwable>) ,public Future<T> onSuccess(AsyncHandler<T>) ,public void run(com.lealone.net.NetInputStream) ,public void setAsyncResult(java.lang.Throwable) ,public void setAsyncResult(T) ,public void setAsyncResult(AsyncResult<T>) ,public void setDbException(com.lealone.common.exceptions.DbException, boolean) ,public void setNetworkTimeout(int) ,public void setPacket(com.lealone.server.protocol.Packet) ,public void setStartTime(long) <variables>private int networkTimeout,private com.lealone.server.protocol.Packet packet,private long startTime
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/link/LinkableList.java
|
LinkableList
|
remove
|
class LinkableList<E extends Linkable<E>> {
private E head;
private E tail;
private int size;
public E getHead() {
return head;
}
public void setHead(E head) {
this.head = head;
}
public E getTail() {
return tail;
}
public void setTail(E tail) {
this.tail = tail;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return size;
}
public void decrementSize() {
size--;
}
public void add(E e) {
size++;
if (head == null) {
head = tail = e;
} else {
tail.setNext(e);
tail = e;
}
}
public void remove(E e) {<FILL_FUNCTION_BODY>}
}
|
boolean found = false;
if (head == e) { // 删除头
found = true;
head = e.getNext();
if (head == null)
tail = null;
} else {
E n = head;
E last = n;
while (n != null) {
if (e == n) {
found = true;
last.setNext(n.getNext());
break;
}
last = n;
n = n.getNext();
}
// 删除尾
if (tail == e) {
found = true;
tail = last;
}
}
if (found)
size--;
| 252
| 179
| 431
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/lock/Lock.java
|
Lock
|
tryLock
|
class Lock {
static final NullLockOwner NULL = new NullLockOwner();
private final AtomicReference<LockOwner> ref = new AtomicReference<>(NULL);
public abstract String getLockType();
public Transaction getTransaction() {
return ref.get().getTransaction();
}
public Object getOldValue() {
return ref.get().getOldValue();
}
public boolean isLockedExclusivelyBy(Session session) {
return ref.get().getTransaction() == session.getTransaction();
}
protected LockOwner createLockOwner(Transaction transaction, Object oldValue) {
return new SimpleLockOwner(transaction);
}
// 子类可以用自己的方式增加锁
protected void addLock(Session session, Transaction t) {
session.addLock(this);
}
public boolean tryLock(Transaction t, Object key, Object oldValue) {<FILL_FUNCTION_BODY>}
public int addWaitingTransaction(Object key, Transaction lockedByTransaction, Session session) {
if (lockedByTransaction == null)
return Transaction.OPERATION_NEED_RETRY;
return lockedByTransaction.addWaitingTransaction(key, session, null);
}
// 允许子类可以覆盖此方法
public void unlock(Session oldSession, boolean succeeded, Session newSession) {
unlock(oldSession, newSession);
}
public void unlock(Session oldSession, Session newSession) {
ref.set(NULL);
}
public LockOwner getLockOwner() {
return ref.get();
}
}
|
Session session = t.getSession();
while (true) {
// 首次调用tryLock时为null
if (ref.get() == NULL) {
LockOwner owner = createLockOwner(t, oldValue);
if (ref.compareAndSet(NULL, owner)) {
addLock(session, t);
return true;
}
}
// 避免重复加锁
Transaction old = ref.get().getTransaction();
if (old == t || old == t.getParentTransaction())
return true;
// 被其他事务占用时需要等待
if (ref.get().getTransaction() != null) {
if (addWaitingTransaction(key, ref.get().getTransaction(),
session) == Transaction.OPERATION_NEED_WAIT) {
return false;
}
}
}
| 402
| 219
| 621
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/EmbeddedScheduler.java
|
SessionInfo
|
executeNextStatement
|
class SessionInfo extends LinkableBase<SessionInfo> {
final Session session;
public SessionInfo(Session session) {
this.session = session;
}
}
@Override
public void addSession(Session session) {
sessions.add(new SessionInfo(session));
session.init();
}
@Override
public void removeSession(Session session) {
if (sessions.isEmpty())
return;
SessionInfo si = sessions.getHead();
while (si != null) {
if (si.session == session) {
sessions.remove(si);
break;
}
si = si.next;
}
}
// --------------------- 实现 SQLStatement 相关的代码 ---------------------
@Override
public void executeNextStatement() {<FILL_FUNCTION_BODY>
|
int priority = PreparedSQLStatement.MIN_PRIORITY - 1; // 最小优先级减一,保证能取到最小的
YieldableCommand last = null;
while (true) {
YieldableCommand c;
if (nextBestCommand != null) {
c = nextBestCommand;
nextBestCommand = null;
} else {
c = getNextBestCommand(null, priority, true);
}
if (c == null) {
runMiscTasks();
c = getNextBestCommand(null, priority, true);
}
if (c == null) {
runPageOperationTasks();
runPendingTransactions();
runMiscTasks();
c = getNextBestCommand(null, priority, true);
if (c == null) {
break;
}
}
try {
currentSession = c.getSession();
c.run();
// 说明没有新的命令了,一直在轮循
if (last == c) {
runPageOperationTasks();
runPendingTransactions();
runMiscTasks();
}
last = c;
} catch (Throwable e) {
logger.warn("Failed to statement: " + c, e);
}
}
| 215
| 319
| 534
|
<methods>public void <init>(int, java.lang.String, int, Map<java.lang.String,java.lang.String>) ,public void accept(java.nio.channels.SelectionKey) ,public void addPendingTransaction(com.lealone.transaction.PendingTransaction) ,public void addPeriodicTask(com.lealone.db.async.AsyncPeriodicTask) ,public void addSession(com.lealone.db.session.Session) ,public void addSessionInfo(java.lang.Object) ,public void addSessionInitTask(java.lang.Object) ,public void addWaitingScheduler(com.lealone.db.scheduler.Scheduler) ,public SchedulerListener<R> createSchedulerListener() ,public void executeNextStatement() ,public com.lealone.db.session.Session getCurrentSession() ,public com.lealone.db.DataBufferFactory getDataBufferFactory() ,public com.lealone.storage.fs.FileStorage getFsyncingFileStorage() ,public int getId() ,public long getLoad() ,public java.lang.String getName() ,public java.lang.Object getNetEventLoop() ,public com.lealone.transaction.PendingTransaction getPendingTransaction() ,public com.lealone.db.scheduler.SchedulerFactory getSchedulerFactory() ,public java.nio.channels.Selector getSelector() ,public com.lealone.db.scheduler.SchedulerThread getThread() ,public void handlePageOperation(com.lealone.storage.page.PageOperation) ,public boolean isFsyncDisabled() ,public boolean isStarted() ,public boolean isStopped() ,public void registerAccepter(com.lealone.server.ProtocolServer, java.nio.channels.ServerSocketChannel) ,public void removePeriodicTask(com.lealone.db.async.AsyncPeriodicTask) ,public void removeSession(com.lealone.db.session.Session) ,public void removeSessionInfo(java.lang.Object) ,public void setCurrentSession(com.lealone.db.session.Session) ,public void setFsyncDisabled(boolean) ,public void setFsyncingFileStorage(com.lealone.storage.fs.FileStorage) ,public void setSchedulerFactory(com.lealone.db.scheduler.SchedulerFactory) ,public synchronized void start() ,public synchronized void stop() ,public java.lang.String toString() ,public void validateSession(boolean) ,public void wakeUpWaitingSchedulers() ,public void wakeUpWaitingSchedulers(boolean) ,public boolean yieldIfNeeded(com.lealone.sql.PreparedSQLStatement) <variables>protected com.lealone.db.session.Session currentSession,protected boolean fsyncDisabled,protected com.lealone.storage.fs.FileStorage fsyncingFileStorage,protected final java.util.concurrent.atomic.AtomicBoolean hasWaitingSchedulers,protected final non-sealed int id,protected final non-sealed long loopInterval,protected final non-sealed java.lang.String name,protected final LinkableList<com.lealone.transaction.PendingTransaction> pendingTransactions,protected final LinkableList<com.lealone.db.async.AsyncPeriodicTask> periodicTasks,protected com.lealone.db.scheduler.SchedulerFactory schedulerFactory,protected boolean started,protected boolean stopped,protected com.lealone.db.scheduler.SchedulerThread thread,protected final non-sealed AtomicReferenceArray<com.lealone.db.scheduler.Scheduler> waitingSchedulers
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerFactoryBase.java
|
LoadBalanceFactory
|
createSchedulerFactory
|
class LoadBalanceFactory extends SchedulerFactoryBase {
protected LoadBalanceFactory(Map<String, String> config, Scheduler[] schedulers) {
super(config, schedulers);
}
@Override
public Scheduler getScheduler() {
long minLoad = Long.MAX_VALUE;
int index = 0;
for (int i = 0, size = schedulers.length; i < size; i++) {
long load = schedulers[i].getLoad();
if (load < minLoad) {
index = i;
minLoad = load;
}
}
return schedulers[index];
}
}
// 变成负数时从0开始
public static int getAndIncrementIndex(AtomicInteger index) {
int i = index.getAndIncrement();
if (i < 0) {
if (index.compareAndSet(i, 1)) {
i = 0;
} else {
i = index.getAndIncrement();
}
}
return i;
}
private static SchedulerFactory defaultSchedulerFactory;
public static void setDefaultSchedulerFactory(SchedulerFactory defaultSchedulerFactory) {
SchedulerFactoryBase.defaultSchedulerFactory = defaultSchedulerFactory;
}
public static SchedulerFactory getDefaultSchedulerFactory() {
return defaultSchedulerFactory;
}
public static SchedulerFactory getDefaultSchedulerFactory(String schedulerClassName,
Map<String, String> config) {
if (SchedulerFactoryBase.getDefaultSchedulerFactory() == null)
initDefaultSchedulerFactory(schedulerClassName, config);
return SchedulerFactoryBase.getDefaultSchedulerFactory();
}
public static synchronized SchedulerFactory initDefaultSchedulerFactory(String schedulerClassName,
Map<String, String> config) {
SchedulerFactory schedulerFactory = SchedulerFactoryBase.getDefaultSchedulerFactory();
if (schedulerFactory == null) {
schedulerFactory = createSchedulerFactory(schedulerClassName, config);
SchedulerFactoryBase.setDefaultSchedulerFactory(schedulerFactory);
}
return schedulerFactory;
}
public static SchedulerFactory createSchedulerFactory(String schedulerClassName,
Map<String, String> config) {<FILL_FUNCTION_BODY>
|
SchedulerFactory schedulerFactory;
String sf = MapUtils.getString(config, "scheduler_factory", null);
if (sf != null) {
schedulerFactory = PluginManager.getPlugin(SchedulerFactory.class, sf);
} else {
Scheduler[] schedulers = createSchedulers(schedulerClassName, config);
schedulerFactory = SchedulerFactory.create(config, schedulers);
}
if (!schedulerFactory.isInited())
schedulerFactory.init(config);
return schedulerFactory;
| 599
| 144
| 743
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public synchronized void close() ,public Map<java.lang.String,java.lang.String> getConfig() ,public java.lang.String getName() ,public Class<? extends com.lealone.db.Plugin> getPluginClass() ,public com.lealone.db.Plugin.State getState() ,public synchronized void init(Map<java.lang.String,java.lang.String>) ,public boolean isInited() ,public boolean isStarted() ,public boolean isStopped() ,public void setName(java.lang.String) ,public void start() ,public void stop() <variables>protected Map<java.lang.String,java.lang.String> config,protected java.lang.String name,protected com.lealone.db.Plugin.State state
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerListener.java
|
SchedulerListener
|
createSchedulerListener
|
class SchedulerListener<R> implements AsyncHandler<AsyncResult<R>> {
protected volatile R result;
protected volatile DbException exception;
protected boolean needWakeUp = true;
public void setNeedWakeUp(boolean needWakeUp) {
this.needWakeUp = needWakeUp;
}
public void setResult(R r) {
handle(new AsyncResult<>(r));
}
public void setException(Throwable t) {
handle(new AsyncResult<>(t));
}
@Override
public void handle(AsyncResult<R> ar) {
if (ar.isSucceeded()) {
result = ar.getResult();
} else {
exception = DbException.convert(ar.getCause());
}
if (needWakeUp)
wakeUp();
}
public abstract R await();
public abstract void wakeUp();
public static interface Factory {
<R> SchedulerListener<R> createSchedulerListener();
}
public static <R> SchedulerListener<R> createSchedulerListener() {<FILL_FUNCTION_BODY>}
}
|
Object object = SchedulerThread.currentObject();
if (object instanceof SchedulerListener.Factory) {
return ((SchedulerListener.Factory) object).createSchedulerListener();
} else {
// 创建一个同步阻塞监听器
return new SchedulerListener<R>() {
private final CountDownLatch latch = new CountDownLatch(1);
@Override
public R await() {
try {
latch.await();
} catch (InterruptedException e) {
exception = DbException.convert(e);
}
if (exception != null)
throw exception;
return result;
}
@Override
public void wakeUp() {
latch.countDown();
}
};
}
| 299
| 200
| 499
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerLock.java
|
SchedulerLock
|
unlock
|
class SchedulerLock {
private static final AtomicReferenceFieldUpdater<SchedulerLock, Scheduler> //
lockUpdater = AtomicReferenceFieldUpdater.newUpdater(SchedulerLock.class, //
Scheduler.class, "lockOwner");
private volatile Scheduler lockOwner;
public boolean tryLock(Scheduler newLockOwner) {
return tryLock(newLockOwner, true);
}
public boolean tryLock(Scheduler newLockOwner, boolean waitingIfLocked) {
// 前面的操作被锁住了就算lockOwner相同后续的也不能再继续
if (newLockOwner == lockOwner)
return false;
while (true) {
if (lockUpdater.compareAndSet(this, null, newLockOwner))
return true;
Scheduler owner = lockOwner;
if (waitingIfLocked && owner != null) {
owner.addWaitingScheduler(newLockOwner);
}
// 解锁了,或者又被其他线程锁住了
if (lockOwner == null || (waitingIfLocked && lockOwner != owner))
continue;
else
return false;
}
}
public void unlock() {<FILL_FUNCTION_BODY>}
public boolean isLocked() {
return lockOwner != null;
}
public Scheduler getLockOwner() {
return lockOwner;
}
}
|
if (lockOwner != null) {
Scheduler owner = lockOwner;
lockOwner = null;
owner.wakeUpWaitingSchedulers();
}
| 366
| 47
| 413
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerThread.java
|
SchedulerThread
|
currentScheduler
|
class SchedulerThread extends Thread {
private final static ThreadLocal<Scheduler> threadLocal = new ThreadLocal<>();
private final Scheduler scheduler;
public SchedulerThread(Scheduler scheduler) {
super(scheduler);
this.scheduler = scheduler;
}
public Scheduler getScheduler() {
return scheduler;
}
public static Session currentSession() {
Object t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler().getCurrentSession();
} else {
return null;
}
}
public static Object currentObject() {
Object t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler();
} else {
return t;
}
}
public static Scheduler currentScheduler() {<FILL_FUNCTION_BODY>}
public static Scheduler currentScheduler(SchedulerFactory sf) {
Thread t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler();
} else {
Scheduler scheduler = threadLocal.get();
if (scheduler == null) {
scheduler = sf.bindScheduler(t);
if (scheduler == null) {
return null;
}
threadLocal.set(scheduler);
}
return scheduler;
}
}
public static void bindScheduler(Scheduler scheduler) {
if (isScheduler())
return;
if (threadLocal.get() != scheduler)
threadLocal.set(scheduler);
}
public static boolean isScheduler() {
return Thread.currentThread() instanceof SchedulerThread;
}
}
|
Thread t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler();
} else {
return null;
}
| 474
| 52
| 526
|
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/session/SessionBase.java
|
SessionBase
|
closeTraceSystem
|
class SessionBase implements Session {
protected boolean autoCommit = true;
protected boolean closed;
protected boolean invalid;
protected String targetNodes;
protected RunMode runMode;
protected String newTargetNodes;
protected int consistencyLevel;
protected TraceSystem traceSystem;
@Override
public boolean isAutoCommit() {
return autoCommit;
}
@Override
public void setAutoCommit(boolean autoCommit) {
this.autoCommit = autoCommit;
}
@Override
public void close() {
closed = true;
}
@Override
public boolean isClosed() {
return closed;
}
/**
* Check if this session is closed and throws an exception if so.
*
* @throws DbException if the session is closed
*/
@Override
public void checkClosed() {
if (isClosed()) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "session closed");
}
}
@Override
public void setInvalid(boolean v) {
invalid = v;
}
@Override
public boolean isInvalid() {
return invalid;
}
@Override
public boolean isValid() {
return !invalid;
}
@Override
public void setTargetNodes(String targetNodes) {
this.targetNodes = targetNodes;
}
@Override
public String getTargetNodes() {
return targetNodes;
}
public void setConsistencyLevel(int consistencyLevel) {
this.consistencyLevel = consistencyLevel;
}
public int getConsistencyLevel() {
return consistencyLevel;
}
@Override
public void setRunMode(RunMode runMode) {
this.runMode = runMode;
}
@Override
public RunMode getRunMode() {
return runMode;
}
@Override
public boolean isRunModeChanged() {
return newTargetNodes != null;
}
@Override
public void runModeChanged(String newTargetNodes) {
this.newTargetNodes = newTargetNodes;
}
public String getNewTargetNodes() {
String nodes = newTargetNodes;
newTargetNodes = null;
return nodes;
}
public Trace getTrace(TraceModuleType traceModuleType) {
if (traceSystem != null)
return traceSystem.getTrace(traceModuleType);
else
return Trace.NO_TRACE;
}
@Override
public Trace getTrace(TraceModuleType traceModuleType, TraceObjectType traceObjectType) {
if (traceSystem != null)
return traceSystem.getTrace(traceModuleType, traceObjectType,
TraceObject.getNextTraceId(traceObjectType));
else
return Trace.NO_TRACE;
}
@Override
public Trace getTrace(TraceModuleType traceModuleType, TraceObjectType traceObjectType,
int traceObjectId) {
if (traceSystem != null)
return traceSystem.getTrace(traceModuleType, traceObjectType, traceObjectId);
else
return Trace.NO_TRACE;
}
protected void initTraceSystem(ConnectionInfo ci) {
String filePrefix = getFilePrefix(SysProperties.CLIENT_TRACE_DIRECTORY, ci.getDatabaseName());
initTraceSystem(ci, filePrefix);
}
protected void initTraceSystem(ConnectionInfo ci, String filePrefix) {
if (traceSystem != null || ci.isTraceDisabled())
return;
traceSystem = new TraceSystem();
String traceLevelFile = ci.getProperty(DbSetting.TRACE_LEVEL_FILE.getName(), null);
if (traceLevelFile != null) {
int level = Integer.parseInt(traceLevelFile);
try {
traceSystem.setLevelFile(level);
if (level > 0) {
String file = FileUtils.createTempFile(filePrefix, Constants.SUFFIX_TRACE_FILE,
false, false);
traceSystem.setFileName(file);
}
} catch (IOException e) {
throw DbException.convertIOException(e, filePrefix);
}
}
String traceLevelSystemOut = ci.getProperty(DbSetting.TRACE_LEVEL_SYSTEM_OUT.getName(), null);
if (traceLevelSystemOut != null) {
int level = Integer.parseInt(traceLevelSystemOut);
traceSystem.setLevelSystemOut(level);
}
}
protected void closeTraceSystem() {<FILL_FUNCTION_BODY>}
private static String getFilePrefix(String dir, String dbName) {
StringBuilder buff = new StringBuilder(dir);
if (!(dir.charAt(dir.length() - 1) == File.separatorChar))
buff.append(File.separatorChar);
for (int i = 0, length = dbName.length(); i < length; i++) {
char ch = dbName.charAt(i);
if (Character.isLetterOrDigit(ch)) {
buff.append(ch);
} else {
buff.append('_');
}
}
return buff.toString();
}
protected Scheduler scheduler;
@Override
public Scheduler getScheduler() {
return scheduler;
}
@Override
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
protected YieldableCommand yieldableCommand;
@Override
public void setYieldableCommand(YieldableCommand yieldableCommand) {
this.yieldableCommand = yieldableCommand;
}
@Override
public YieldableCommand getYieldableCommand() {
return yieldableCommand;
}
@Override
public YieldableCommand getYieldableCommand(boolean checkTimeout, TimeoutListener timeoutListener) {
return yieldableCommand;
}
@Override
public void init() {
}
}
|
if (traceSystem != null) {
traceSystem.close();
traceSystem = null;
}
| 1,544
| 31
| 1,575
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/BlobBase.java
|
BlobBase
|
getBytes
|
class BlobBase extends TraceObject implements Blob {
protected Value value;
public Value getValue() {
return value;
}
/**
* Returns the length.
*
* @return the length
* @throws SQLException
*/
@Override
public long length() throws SQLException {
try {
debugCodeCall("length");
checkClosed();
if (value.getType() == Value.BLOB) {
long precision = value.getPrecision();
if (precision > 0) {
return precision;
}
}
return IOUtils.copyAndCloseInput(value.getInputStream(), null);
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* [Not supported] Truncates the object.
*
* @param len the new length
* @throws SQLException
*/
@Override
public void truncate(long len) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns some bytes of the object.
*
* @param pos the index, the first byte is at position 1
* @param length the number of bytes
* @return the bytes, at most length bytes
* @throws SQLException
*/
@Override
public byte[] getBytes(long pos, int length) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* Fills the Blob. This is only supported for new, empty Blob objects that
* were created with Connection.createBlob(). The position
* must be 1, meaning the whole Blob data is set.
*
* @param pos where to start writing (the first byte is at position 1)
* @param bytes the bytes to set
* @return the length of the added data
*/
@Override
public abstract int setBytes(long pos, byte[] bytes) throws SQLException;
/**
* [Not supported] Sets some bytes of the object.
*
* @param pos the write position
* @param bytes the bytes to set
* @param offset the bytes offset
* @param len the number of bytes to write
* @return how many bytes have been written
* @throws SQLException
*/
@Override
public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns the input stream.
*
* @return the input stream
* @throws SQLException
*/
@Override
public InputStream getBinaryStream() throws SQLException {
try {
debugCodeCall("getBinaryStream");
checkClosed();
return value.getInputStream();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Get a writer to update the Blob. This is only supported for new, empty
* Blob objects that were created with Connection.createBlob(). The Blob is
* created in a separate thread, and the object is only updated when
* OutputStream.close() is called. The position must be 1, meaning the whole
* Blob data is set.
*
* @param pos where to start writing (the first byte is at position 1)
* @return an output stream
*/
@Override
public abstract OutputStream setBinaryStream(long pos) throws SQLException;
/**
* [Not supported] Searches a pattern and return the position.
*
* @param pattern the pattern to search
* @param start the index, the first byte is at position 1
* @return the position (first byte is at position 1), or -1 for not found
* @throws SQLException
*/
@Override
public long position(byte[] pattern, long start) throws SQLException {
if (isDebugEnabled()) {
debugCode("position(" + quoteBytes(pattern) + ", " + start + ");");
}
if (Constants.BLOB_SEARCH) {
try {
checkClosed();
if (pattern == null) {
return -1;
}
if (pattern.length == 0) {
return 1;
}
// TODO performance: blob pattern search is slow
BufferedInputStream in = new BufferedInputStream(value.getInputStream());
IOUtils.skipFully(in, start - 1);
int pos = 0;
int patternPos = 0;
while (true) {
int x = in.read();
if (x < 0) {
break;
}
if (x == (pattern[patternPos] & 0xff)) {
if (patternPos == 0) {
in.mark(pattern.length);
}
if (patternPos == pattern.length) {
return pos - patternPos;
}
patternPos++;
} else {
if (patternPos > 0) {
in.reset();
pos -= patternPos;
}
}
pos++;
}
return -1;
} catch (Exception e) {
throw logAndConvert(e);
}
}
throw unsupported("LOB search");
}
/**
* [Not supported] Searches a pattern and return the position.
*
* @param blobPattern the pattern to search
* @param start the index, the first byte is at position 1
* @return the position (first byte is at position 1), or -1 for not found
* @throws SQLException
*/
@Override
public long position(Blob blobPattern, long start) throws SQLException {
if (isDebugEnabled()) {
debugCode("position(blobPattern, " + start + ");");
}
if (Constants.BLOB_SEARCH) {
try {
checkClosed();
if (blobPattern == null) {
return -1;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = blobPattern.getBinaryStream();
while (true) {
int x = in.read();
if (x < 0) {
break;
}
out.write(x);
}
return position(out.toByteArray(), start);
} catch (Exception e) {
throw logAndConvert(e);
}
}
throw unsupported("LOB subset");
}
/**
* Release all resources of this object.
*/
@Override
public void free() {
debugCodeCall("free");
value = null;
}
/**
* [Not supported] Returns the input stream, starting from an offset.
*
* @param pos where to start reading
* @param length the number of bytes that will be read
* @return the input stream to read
* @throws SQLException
*/
@Override
public InputStream getBinaryStream(long pos, long length) throws SQLException {
throw unsupported("LOB update");
}
protected void checkClosed() {
if (value == null) {
throw DbException.get(ErrorCode.OBJECT_CLOSED);
}
}
/**
* INTERNAL
*/
@Override
public String toString() {
return getTraceObjectName() + ": " + (value == null ? "null" : value.getTraceSQL());
}
}
|
try {
if (isDebugEnabled()) {
debugCode("getBytes(" + pos + ", " + length + ");");
}
checkClosed();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = value.getInputStream();
try {
IOUtils.skipFully(in, pos - 1);
IOUtils.copy(in, out, length);
} finally {
in.close();
}
return out.toByteArray();
} catch (Exception e) {
throw logAndConvert(e);
}
| 1,846
| 143
| 1,989
|
<methods>public non-sealed void <init>() ,public static int getNextTraceId(com.lealone.common.trace.TraceObjectType) ,public int getTraceId() ,public java.lang.String getTraceObjectName() <variables>private static final non-sealed java.util.concurrent.atomic.AtomicInteger[] ID,protected com.lealone.common.trace.Trace trace
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ClobBase.java
|
ClobBase
|
length
|
class ClobBase extends TraceObject implements Clob, NClob {
protected Value value;
public Value getValue() {
return value;
}
/**
* Returns the length.
*
* @return the length
*/
@Override
public long length() throws SQLException {<FILL_FUNCTION_BODY>}
/**
* [Not supported] Truncates the object.
*/
@Override
public void truncate(long len) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns the input stream.
*
* @return the input stream
*/
@Override
public InputStream getAsciiStream() throws SQLException {
try {
debugCodeCall("getAsciiStream");
checkClosed();
String s = value.getString();
return IOUtils.getInputStreamFromString(s);
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* [Not supported] Returns an output stream.
*/
@Override
public OutputStream setAsciiStream(long pos) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns the reader.
*
* @return the reader
*/
@Override
public Reader getCharacterStream() throws SQLException {
try {
debugCodeCall("getCharacterStream");
checkClosed();
return value.getReader();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Get a writer to update the Clob. This is only supported for new, empty
* Clob objects that were created with Connection.createClob() or
* createNClob(). The Clob is created in a separate thread, and the object
* is only updated when Writer.close() is called. The position must be 1,
* meaning the whole Clob data is set.
*
* @param pos where to start writing (the first character is at position 1)
* @return a writer
*/
@Override
public abstract Writer setCharacterStream(long pos) throws SQLException;
/**
* Returns a substring.
*
* @param pos the position (the first character is at position 1)
* @param length the number of characters
* @return the string
*/
@Override
public String getSubString(long pos, int length) throws SQLException {
try {
if (isDebugEnabled()) {
debugCode("getSubString(" + pos + ", " + length + ");");
}
checkClosed();
if (pos < 1) {
throw DbException.getInvalidValueException("pos", pos);
}
if (length < 0) {
throw DbException.getInvalidValueException("length", length);
}
StringWriter writer = new StringWriter(Math.min(Constants.IO_BUFFER_SIZE, length));
Reader reader = value.getReader();
try {
IOUtils.skipFully(reader, pos - 1);
IOUtils.copyAndCloseInput(reader, writer, length);
} finally {
reader.close();
}
return writer.toString();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Fills the Clob. This is only supported for new, empty Clob objects that
* were created with Connection.createClob() or createNClob(). The position
* must be 1, meaning the whole Clob data is set.
*
* @param pos where to start writing (the first character is at position 1)
* @param str the string to add
* @return the length of the added text
*/
@Override
public abstract int setString(long pos, String str) throws SQLException;
/**
* [Not supported] Sets a substring.
*/
@Override
public int setString(long pos, String str, int offset, int len) throws SQLException {
throw unsupported("LOB update");
}
/**
* [Not supported] Searches a pattern and return the position.
*/
@Override
public long position(String pattern, long start) throws SQLException {
throw unsupported("LOB search");
}
/**
* [Not supported] Searches a pattern and return the position.
*/
@Override
public long position(Clob clobPattern, long start) throws SQLException {
throw unsupported("LOB search");
}
/**
* Release all resources of this object.
*/
@Override
public void free() {
debugCodeCall("free");
value = null;
}
/**
* [Not supported] Returns the reader, starting from an offset.
*/
@Override
public Reader getCharacterStream(long pos, long length) throws SQLException {
throw unsupported("LOB subset");
}
protected void checkClosed() {
if (value == null) {
throw DbException.get(ErrorCode.OBJECT_CLOSED);
}
}
/**
* INTERNAL
*/
@Override
public String toString() {
return getTraceObjectName() + ": " + (value == null ? "null" : value.getTraceSQL());
}
}
|
try {
debugCodeCall("length");
checkClosed();
if (value.getType() == Value.CLOB) {
long precision = value.getPrecision();
if (precision > 0) {
return precision;
}
}
return IOUtils.copyAndCloseInput(value.getReader(), null, Long.MAX_VALUE);
} catch (Exception e) {
throw logAndConvert(e);
}
| 1,346
| 114
| 1,460
|
<methods>public non-sealed void <init>() ,public static int getNextTraceId(com.lealone.common.trace.TraceObjectType) ,public int getTraceId() ,public java.lang.String getTraceObjectName() <variables>private static final non-sealed java.util.concurrent.atomic.AtomicInteger[] ID,protected com.lealone.common.trace.Trace trace
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/CompareMode.java
|
CompareMode
|
getCollator
|
class CompareMode {
/**
* This constant means there is no collator set, and the default string
* comparison is to be used.
*/
public static final String OFF = "OFF";
/**
* This constant means the default collator should be used, even if ICU4J is
* in the classpath.
*/
public static final String DEFAULT = "DEFAULT_";
/**
* This constant means ICU4J should be used (this will fail if it is not in
* the classpath).
*/
public static final String ICU4J = "ICU4J_";
/**
* This constant means that the BINARY columns are sorted as if the bytes
* were signed.
*/
public static final String SIGNED = "SIGNED";
/**
* This constant means that the BINARY columns are sorted as if the bytes
* were unsigned.
*/
public static final String UNSIGNED = "UNSIGNED";
private static CompareMode lastUsed;
private static final boolean CAN_USE_ICU4J;
static {
boolean b = false;
try {
Class.forName("com.ibm.icu.text.Collator");
b = true;
} catch (Exception e) {
// ignore
}
CAN_USE_ICU4J = b;
}
private final String name;
private final int strength;
/** if true, sort BINARY columns as if they contain unsigned bytes */
private final boolean binaryUnsigned;
protected CompareMode(String name, int strength, boolean binaryUnsigned) {
this.name = name;
this.strength = strength;
this.binaryUnsigned = binaryUnsigned;
}
/**
* Create a new compare mode with the given collator and strength. If
* required, a new CompareMode is created, or if possible the last one is
* returned. A cache is used to speed up comparison when using a collator;
* CollationKey objects are cached.
*
* @param name the collation name or null
* @param strength the collation strength
* @param binaryUnsigned whether to compare binaries as unsigned
* @return the compare mode
*/
public static synchronized CompareMode getInstance(String name, int strength,
boolean binaryUnsigned) {
if (lastUsed != null) {
if (StringUtils.equals(lastUsed.name, name) && lastUsed.strength == strength
&& lastUsed.binaryUnsigned == binaryUnsigned) {
return lastUsed;
}
}
if (name == null || name.equals(OFF)) {
lastUsed = new CompareMode(name, strength, binaryUnsigned);
} else {
boolean useICU4J;
if (name.startsWith(ICU4J)) {
useICU4J = true;
name = name.substring(ICU4J.length());
} else if (name.startsWith(DEFAULT)) {
useICU4J = false;
name = name.substring(DEFAULT.length());
} else {
useICU4J = CAN_USE_ICU4J;
}
if (useICU4J) {
lastUsed = new CompareModeIcu4J(name, strength, binaryUnsigned);
} else {
lastUsed = new CompareModeDefault(name, strength, binaryUnsigned);
}
}
return lastUsed;
}
/**
* Compare two characters in a string.
*
* @param a the first string
* @param ai the character index in the first string
* @param b the second string
* @param bi the character index in the second string
* @param ignoreCase true if a case-insensitive comparison should be made
* @return true if the characters are equals
*/
public boolean equalsChars(String a, int ai, String b, int bi, boolean ignoreCase) {
char ca = a.charAt(ai);
char cb = b.charAt(bi);
if (ignoreCase) {
ca = Character.toUpperCase(ca);
cb = Character.toUpperCase(cb);
}
return ca == cb;
}
/**
* Compare two strings.
*
* @param a the first string
* @param b the second string
* @param ignoreCase true if a case-insensitive comparison should be made
* @return -1 if the first string is 'smaller', 1 if the second string is
* smaller, and 0 if they are equal
*/
public int compareString(String a, String b, boolean ignoreCase) {
if (ignoreCase) {
return a.compareToIgnoreCase(b);
}
return a.compareTo(b);
}
/**
* Get the collation name.
*
* @param l the locale
* @return the name of the collation
*/
public static String getName(Locale l) {
Locale english = Locale.ENGLISH;
String name = l.getDisplayLanguage(english) + ' ' + l.getDisplayCountry(english) + ' '
+ l.getVariant();
name = StringUtils.toUpperEnglish(name.trim().replace(' ', '_'));
return name;
}
/**
* Compare name name of the locale with the given name. The case of the name
* is ignored.
*
* @param locale the locale
* @param name the name
* @return true if they match
*/
static boolean compareLocaleNames(Locale locale, String name) {
return name.equalsIgnoreCase(locale.toString()) || name.equalsIgnoreCase(getName(locale));
}
/**
* Get the collator object for the given language name or language / country
* combination.
*
* @param name the language name
* @return the collator
*/
public static Collator getCollator(String name) {<FILL_FUNCTION_BODY>}
public String getName() {
return name == null ? OFF : name;
}
public int getStrength() {
return strength;
}
public boolean isBinaryUnsigned() {
return binaryUnsigned;
}
}
|
Collator result = null;
if (name.startsWith(ICU4J)) {
name = name.substring(ICU4J.length());
} else if (name.startsWith(DEFAULT)) {
name = name.substring(DEFAULT.length());
}
if (name.length() == 2) {
Locale locale = new Locale(StringUtils.toLowerEnglish(name), "");
if (compareLocaleNames(locale, name)) {
result = Collator.getInstance(locale);
}
} else if (name.length() == 5) {
// LL_CC (language_country)
int idx = name.indexOf('_');
if (idx >= 0) {
String language = StringUtils.toLowerEnglish(name.substring(0, idx));
String country = name.substring(idx + 1);
Locale locale = new Locale(language, country);
if (compareLocaleNames(locale, name)) {
result = Collator.getInstance(locale);
}
}
}
if (result == null) {
for (Locale locale : Collator.getAvailableLocales()) {
if (compareLocaleNames(locale, name)) {
result = Collator.getInstance(locale);
break;
}
}
}
return result;
| 1,589
| 332
| 1,921
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/CompareModeDefault.java
|
CompareModeDefault
|
compareString
|
class CompareModeDefault extends CompareMode {
private final Collator collator;
private final SmallLRUCache<String, CollationKey> collationKeys;
protected CompareModeDefault(String name, int strength, boolean binaryUnsigned) {
super(name, strength, binaryUnsigned);
collator = CompareMode.getCollator(name);
if (collator == null) {
throw DbException.getInternalError(name);
}
collator.setStrength(strength);
int cacheSize = SysProperties.COLLATOR_CACHE_SIZE;
if (cacheSize != 0) {
collationKeys = SmallLRUCache.newInstance(cacheSize);
} else {
collationKeys = null;
}
}
@Override
public int compareString(String a, String b, boolean ignoreCase) {<FILL_FUNCTION_BODY>}
@Override
public boolean equalsChars(String a, int ai, String b, int bi, boolean ignoreCase) {
return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1), ignoreCase) == 0;
}
private CollationKey getKey(String a) {
synchronized (collationKeys) {
CollationKey key = collationKeys.get(a);
if (key == null) {
key = collator.getCollationKey(a);
collationKeys.put(a, key);
}
return key;
}
}
}
|
if (ignoreCase) {
// this is locale sensitive
a = a.toUpperCase();
b = b.toUpperCase();
}
int comp;
if (collationKeys != null) {
CollationKey aKey = getKey(a);
CollationKey bKey = getKey(b);
comp = aKey.compareTo(bKey);
} else {
comp = collator.compare(a, b);
}
return comp;
| 385
| 125
| 510
|
<methods>public int compareString(java.lang.String, java.lang.String, boolean) ,public boolean equalsChars(java.lang.String, int, java.lang.String, int, boolean) ,public static java.text.Collator getCollator(java.lang.String) ,public static synchronized com.lealone.db.value.CompareMode getInstance(java.lang.String, int, boolean) ,public static java.lang.String getName(java.util.Locale) ,public java.lang.String getName() ,public int getStrength() ,public boolean isBinaryUnsigned() <variables>private static final non-sealed boolean CAN_USE_ICU4J,public static final java.lang.String DEFAULT,public static final java.lang.String ICU4J,public static final java.lang.String OFF,public static final java.lang.String SIGNED,public static final java.lang.String UNSIGNED,private final non-sealed boolean binaryUnsigned,private static com.lealone.db.value.CompareMode lastUsed,private final non-sealed java.lang.String name,private final non-sealed int strength
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/CompareModeIcu4J.java
|
CompareModeIcu4J
|
equalsChars
|
class CompareModeIcu4J extends CompareMode {
private final Comparator<String> collator;
protected CompareModeIcu4J(String name, int strength, boolean binaryUnsigned) {
super(name, strength, binaryUnsigned);
collator = getIcu4jCollator(name, strength);
}
@Override
public int compareString(String a, String b, boolean ignoreCase) {
if (ignoreCase) {
a = a.toUpperCase();
b = b.toUpperCase();
}
return collator.compare(a, b);
}
@Override
public boolean equalsChars(String a, int ai, String b, int bi, boolean ignoreCase) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
private static Comparator<String> getIcu4jCollator(String name, int strength) {
try {
Comparator<String> result = null;
Class<?> collatorClass = Utils.loadUserClass("com.ibm.icu.text.Collator");
Method getInstanceMethod = collatorClass.getMethod("getInstance", Locale.class);
if (name.length() == 2) {
Locale locale = new Locale(StringUtils.toLowerEnglish(name), "");
if (compareLocaleNames(locale, name)) {
result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
}
} else if (name.length() == 5) {
// LL_CC (language_country)
int idx = name.indexOf('_');
if (idx >= 0) {
String language = StringUtils.toLowerEnglish(name.substring(0, idx));
String country = name.substring(idx + 1);
Locale locale = new Locale(language, country);
if (compareLocaleNames(locale, name)) {
result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
}
}
}
if (result == null) {
for (Locale locale : (Locale[]) collatorClass.getMethod("getAvailableLocales")
.invoke(null)) {
if (compareLocaleNames(locale, name)) {
result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
break;
}
}
}
if (result == null) {
throw DbException.getInvalidValueException("collator", name);
}
collatorClass.getMethod("setStrength", int.class).invoke(result, strength);
return result;
} catch (Exception e) {
throw DbException.convert(e);
}
}
}
|
return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1), ignoreCase) == 0;
| 689
| 38
| 727
|
<methods>public int compareString(java.lang.String, java.lang.String, boolean) ,public boolean equalsChars(java.lang.String, int, java.lang.String, int, boolean) ,public static java.text.Collator getCollator(java.lang.String) ,public static synchronized com.lealone.db.value.CompareMode getInstance(java.lang.String, int, boolean) ,public static java.lang.String getName(java.util.Locale) ,public java.lang.String getName() ,public int getStrength() ,public boolean isBinaryUnsigned() <variables>private static final non-sealed boolean CAN_USE_ICU4J,public static final java.lang.String DEFAULT,public static final java.lang.String ICU4J,public static final java.lang.String OFF,public static final java.lang.String SIGNED,public static final java.lang.String UNSIGNED,private final non-sealed boolean binaryUnsigned,private static com.lealone.db.value.CompareMode lastUsed,private final non-sealed java.lang.String name,private final non-sealed int strength
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ReadonlyArray.java
|
ReadonlyArray
|
toString
|
class ReadonlyArray extends ArrayBase {
{
this.trace = Trace.NO_TRACE;
}
public ReadonlyArray(Value value) {
this.value = value;
}
public ReadonlyArray(String value) {
setValue(value);
}
public ReadonlyArray(Object value) {
if (value instanceof List) {
setValue((List<?>) value);
} else {
setValue(value.toString());
}
}
public ReadonlyArray(Object... values) {
setValue(values);
}
public ReadonlyArray(List<String> list) {
setValue(list);
}
private void setValue(List<?> list) {
setValue(list.toArray());
}
private void setValue(Object... values) {
value = DataType.convertToValue(values, Value.ARRAY);
}
private void setValue(String value) {
this.value = ValueString.get(value);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (value instanceof ValueArray) {
ValueArray va = (ValueArray) value;
StatementBuilder buff = new StatementBuilder("[");
for (Value v : va.getList()) {
buff.appendExceptFirst(", ");
buff.append(v.getString());
}
return buff.append(']').toString();
}
return value.toString();
| 292
| 97
| 389
|
<methods>public non-sealed void <init>() ,public void free() ,public java.lang.Object getArray() throws java.sql.SQLException,public java.lang.Object getArray(Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public java.lang.Object getArray(long, int) throws java.sql.SQLException,public java.lang.Object getArray(long, int, Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public int getBaseType() throws java.sql.SQLException,public java.lang.String getBaseTypeName() throws java.sql.SQLException,public java.sql.ResultSet getResultSet() throws java.sql.SQLException,public java.sql.ResultSet getResultSet(Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public java.sql.ResultSet getResultSet(long, int) throws java.sql.SQLException,public java.sql.ResultSet getResultSet(long, int, Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public java.lang.String toString() <variables>protected com.lealone.db.value.Value value
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueArray.java
|
ValueArray
|
get
|
class ValueArray extends Value {
private final Class<?> componentType;
private final Value[] values;
private int hash;
private ValueArray(Class<?> componentType, Value[] list) {
this.componentType = componentType;
this.values = list;
}
private ValueArray(Value[] list) {
this(Object.class, list);
}
/**
* Get or create a array value for the given value array.
* Do not clone the data.
*
* @param list the value array
* @return the value
*/
public static ValueArray get(Value[] list) {
return new ValueArray(list);
}
public static ValueArray get(java.sql.Array array) {<FILL_FUNCTION_BODY>}
/**
* Get or create a array value for the given value array.
* Do not clone the data.
*
* @param componentType the array class (null for Object[])
* @param list the value array
* @return the value
*/
public static ValueArray get(Class<?> componentType, Value[] list) {
return new ValueArray(componentType, list);
}
@Override
public int hashCode() {
if (hash != 0) {
return hash;
}
int h = 1;
for (Value v : values) {
h = h * 31 + v.hashCode();
}
hash = h;
return h;
}
public Value[] getList() {
return values;
}
@Override
public int getType() {
return Value.ARRAY;
}
public Class<?> getComponentType() {
return componentType;
}
@Override
public long getPrecision() {
long p = 0;
for (Value v : values) {
p += v.getPrecision();
}
return p;
}
@Override
public String getString() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getString());
}
return buff.append(')').toString();
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueArray v = (ValueArray) o;
if (values == v.values) {
return 0;
}
int l = values.length;
int ol = v.values.length;
int len = Math.min(l, ol);
for (int i = 0; i < len; i++) {
Value v1 = values[i];
Value v2 = v.values[i];
int comp = v1.compareTo(v2, mode);
if (comp != 0) {
return comp;
}
}
return l > ol ? 1 : l == ol ? 0 : -1;
}
@Override
public Object getObject() {
int len = values.length;
Object[] list = (Object[]) Array.newInstance(componentType, len);
for (int i = 0; i < len; i++) {
list[i] = values[i].getObject();
}
return list;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) {
throw throwUnsupportedExceptionForType("PreparedStatement.set");
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getSQL());
}
if (values.length == 1) {
buff.append(',');
}
return buff.append(')').toString();
}
@Override
public String getTraceSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getTraceSQL());
}
return buff.append(')').toString();
}
@Override
public int getDisplaySize() {
long size = 0;
for (Value v : values) {
size += v.getDisplaySize();
}
return MathUtils.convertLongToInt(size);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueArray)) {
return false;
}
ValueArray v = (ValueArray) other;
if (values == v.values) {
return true;
}
int len = values.length;
if (len != v.values.length) {
return false;
}
for (int i = 0; i < len; i++) {
if (!values[i].equals(v.values[i])) {
return false;
}
}
return true;
}
@Override
public int getMemory() {
int memory = 32;
for (Value v : values) {
memory += v.getMemory() + Constants.MEMORY_POINTER;
}
return memory;
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (!force) {
return this;
}
int length = values.length;
Value[] newValues = new Value[length];
int i = 0;
boolean modified = false;
for (; i < length; i++) {
Value old = values[i];
Value v = old.convertPrecision(precision, true);
if (v != old) {
modified = true;
}
// empty byte arrays or strings have precision 0
// they count as precision 1 here
precision -= Math.max(1, v.getPrecision());
if (precision < 0) {
break;
}
newValues[i] = v;
}
if (i < length) {
return get(componentType, Arrays.copyOf(newValues, i));
}
return modified ? get(componentType, newValues) : this;
}
public Value getValue(int i) {
return values[i];
}
@Override
public Value add(Value v) {
ValueArray va = (ValueArray) v;
List<Value> newValues = new ArrayList<>(values.length + va.values.length);
newValues.addAll(Arrays.asList(values));
newValues.addAll(Arrays.asList(va.values));
return ValueArray.get(componentType, newValues.toArray(new Value[0]));
}
@Override
public Value subtract(Value v) {
ValueArray va = (ValueArray) v;
List<Value> newValues = new ArrayList<>(Math.abs(values.length - va.values.length));
newValues.addAll(Arrays.asList(values));
newValues.removeAll(Arrays.asList(va.values));
return ValueArray.get(componentType, newValues.toArray(new Value[0]));
}
}
|
Object[] objArray;
try {
objArray = (Object[]) array.getArray();
int size = objArray.length;
Value[] values = new Value[size];
for (int i = 0; i < size; i++) {
values[i] = ValueString.get(objArray[i].toString());
}
return new ValueArray(values);
} catch (SQLException e) {
throw DbException.convert(e);
}
| 1,825
| 121
| 1,946
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueBoolean.java
|
ValueBoolean
|
compareSecure
|
class ValueBoolean extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 1;
/**
* The maximum display size of a boolean.
* Example: FALSE
*/
public static final int DISPLAY_SIZE = 5;
/**
* Of type Object so that Tomcat doesn't set it to null.
*/
public static final ValueBoolean TRUE = new ValueBoolean(true);
public static final ValueBoolean FALSE = new ValueBoolean(false);
private final boolean value;
private ValueBoolean(boolean value) {
this.value = value;
}
@Override
public int getType() {
return Value.BOOLEAN;
}
@Override
public String getSQL() {
return getString();
}
@Override
public String getString() {
return value ? "TRUE" : "FALSE";
}
@Override
public Value negate() {
return value ? FALSE : TRUE;
}
@Override
public boolean getBoolean() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {<FILL_FUNCTION_BODY>}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value ? 1 : 0;
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setBoolean(parameterIndex, value);
}
/**
* Get the boolean value for the given boolean.
*
* @param b the boolean
* @return the value
*/
public static ValueBoolean get(boolean b) {
return b ? TRUE : FALSE;
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
// there are only ever two instances, so the instance must match
return this == other;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return TYPE_BOOLEAN;
}
@Override
public int compare(Object aObj, Object bObj) {
Boolean a = (Boolean) aObj;
Boolean b = (Boolean) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
write0(buff, ((Boolean) obj).booleanValue());
}
@Override
public void writeValue(DataBuffer buff, Value v) {
write0(buff, v.getBoolean());
}
private void write0(DataBuffer buff, boolean v) {
buff.put((byte) (v ? TAG_BOOLEAN_TRUE : TYPE_BOOLEAN));
}
@Override
public Value readValue(ByteBuffer buff, int tag) {
if (tag == TYPE_BOOLEAN)
return ValueBoolean.get(false);
else
return ValueBoolean.get(true);
}
};
}
|
boolean v2 = ((ValueBoolean) o).value;
boolean v = value;
return (v == v2) ? 0 : (v ? 1 : -1);
| 865
| 46
| 911
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueByte.java
|
ValueByte
|
divide
|
class ValueByte extends Value {
/**
* The precision in digits.
*/
static final int PRECISION = 3;
/**
* The display size for a byte.
* Example: -127
*/
static final int DISPLAY_SIZE = 4;
private final byte value;
private ValueByte(byte value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueByte other = (ValueByte) v;
return checkRange(value + other.value);
}
private static ValueByte checkRange(int x) {
if (x < Byte.MIN_VALUE || x > Byte.MAX_VALUE) {
throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, Integer.toString(x));
}
return ValueByte.get((byte) x);
}
@Override
public int getSignum() {
return Integer.signum(value);
}
@Override
public Value negate() {
return checkRange(-(int) value);
}
@Override
public Value subtract(Value v) {
ValueByte other = (ValueByte) v;
return checkRange(value - other.value);
}
@Override
public Value multiply(Value v) {
ValueByte other = (ValueByte) v;
return checkRange(value * other.value);
}
@Override
public Value divide(Value v) {<FILL_FUNCTION_BODY>}
@Override
public Value modulus(Value v) {
ValueByte other = (ValueByte) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueByte.get((byte) (value % other.value));
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.BYTE;
}
@Override
public byte getByte() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueByte v = (ValueByte) o;
return MathUtils.compareInt(value, v.value);
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value;
}
@Override
public Object getObject() {
return Byte.valueOf(value);
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setByte(parameterIndex, value);
}
/**
* Get or create byte value for the given byte.
*
* @param i the byte
* @return the value
*/
public static ValueByte get(byte i) {
return (ValueByte) Value.cache(new ValueByte(i));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueByte && value == ((ValueByte) other).value;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return BYTE;
}
@Override
public int compare(Object aObj, Object bObj) {
Byte a = (Byte) aObj;
Byte b = (Byte) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
buff.put((byte) Value.BYTE).put(((Byte) obj).byteValue());
}
@Override
public void writeValue(DataBuffer buff, Value v) {
buff.put((byte) Value.BYTE).put(v.getByte());
}
@Override
public Value readValue(ByteBuffer buff) {
return ValueByte.get(buff.get());
}
};
}
|
ValueByte other = (ValueByte) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueByte.get((byte) (value / other.value));
| 1,126
| 74
| 1,200
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueBytes.java
|
ValueBytes
|
getNoCopy
|
class ValueBytes extends Value {
private static final ValueBytes EMPTY = new ValueBytes(Utils.EMPTY_BYTES);
/**
* The value.
*/
protected byte[] value;
/**
* The hash code.
*/
protected int hash;
protected ValueBytes(byte[] v) {
this.value = v;
}
/**
* Get or create a bytes value for the given byte array.
* Clone the data.
*
* @param b the byte array
* @return the value
*/
public static ValueBytes get(byte[] b) {
if (b.length == 0) {
return EMPTY;
}
b = Utils.cloneByteArray(b);
return getNoCopy(b);
}
/**
* Get or create a bytes value for the given byte array.
* Do not clone the date.
*
* @param b the byte array
* @return the value
*/
public static ValueBytes getNoCopy(byte[] b) {<FILL_FUNCTION_BODY>}
@Override
public int getType() {
return Value.BYTES;
}
@Override
public String getSQL() {
return "X'" + StringUtils.convertBytesToHex(getBytesNoCopy()) + "'";
}
@Override
public byte[] getBytesNoCopy() {
return value;
}
@Override
public byte[] getBytes() {
return Utils.cloneByteArray(getBytesNoCopy());
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
byte[] v2 = ((ValueBytes) v).value;
if (mode.isBinaryUnsigned()) {
return Utils.compareNotNullUnsigned(value, v2);
}
return Utils.compareNotNullSigned(value, v2);
}
@Override
public String getString() {
return StringUtils.convertBytesToHex(value);
}
@Override
public long getPrecision() {
return value.length;
}
@Override
public int hashCode() {
if (hash == 0) {
hash = Utils.getByteArrayHash(value);
}
return hash;
}
@Override
public Object getObject() {
return getBytes();
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setBytes(parameterIndex, value);
}
@Override
public int getDisplaySize() {
return MathUtils.convertLongToInt(value.length * 2L);
}
@Override
public int getMemory() {
return value.length + 24;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueBytes && Arrays.equals(value, ((ValueBytes) other).value);
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (value.length <= precision) {
return this;
}
int len = MathUtils.convertLongToInt(precision);
byte[] buff = new byte[len];
System.arraycopy(value, 0, buff, 0, len);
return get(buff);
}
}
|
if (b.length == 0) {
return EMPTY;
}
ValueBytes obj = new ValueBytes(b);
if (b.length > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
return (ValueBytes) Value.cache(obj);
| 853
| 86
| 939
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueDate.java
|
ValueDate
|
appendDate
|
class ValueDate extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 8;
/**
* The display size of the textual representation of a date.
* Example: 2000-01-02
*/
public static final int DISPLAY_SIZE = 10;
private final long dateValue;
private ValueDate(long dateValue) {
this.dateValue = dateValue;
}
/**
* Get or create a date value for the given date.
*
* @param dateValue the date value
* @return the value
*/
public static ValueDate fromDateValue(long dateValue) {
return (ValueDate) Value.cache(new ValueDate(dateValue));
}
/**
* Get or create a date value for the given date.
*
* @param date the date
* @return the value
*/
public static ValueDate get(Date date) {
return fromDateValue(DateTimeUtils.dateValueFromDate(date.getTime()));
}
/**
* Parse a string to a ValueDate.
*
* @param s the string to parse
* @return the date
*/
public static ValueDate parse(String s) {
try {
return fromDateValue(DateTimeUtils.parseDateValue(s, 0, s.length()));
} catch (Exception e) {
throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2, e, "DATE", s);
}
}
public long getDateValue() {
return dateValue;
}
@Override
public Date getDate() {
return DateTimeUtils.convertDateValueToDate(dateValue);
}
@Override
public int getType() {
return Value.DATE;
}
@Override
public String getString() {
StringBuilder buff = new StringBuilder(DISPLAY_SIZE);
appendDate(buff, dateValue);
return buff.toString();
}
@Override
public String getSQL() {
return "DATE '" + getString() + "'";
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
return MathUtils.compareLong(dateValue, ((ValueDate) o).dateValue);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
return other instanceof ValueDate && dateValue == (((ValueDate) other).dateValue);
}
@Override
public int hashCode() {
return (int) (dateValue ^ (dateValue >>> 32));
}
@Override
public Object getObject() {
return getDate();
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setDate(parameterIndex, getDate());
}
/**
* Append a date to the string builder.
*
* @param buff the target string builder
* @param dateValue the date value
*/
static void appendDate(StringBuilder buff, long dateValue) {<FILL_FUNCTION_BODY>}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return DATE;
}
@Override
public int compare(Object aObj, Object bObj) {
Date a = (Date) aObj;
Date b = (Date) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 24;
}
@Override
public void write(DataBuffer buff, Object obj) {
Date d = (Date) obj;
write0(buff, d.getTime());
}
@Override
public void writeValue(DataBuffer buff, Value v) {
long d = ((ValueDate) v).getDateValue();
write0(buff, d);
}
private void write0(DataBuffer buff, long v) {
buff.put((byte) Value.DATE).putVarLong(v);
}
@Override
public Value readValue(ByteBuffer buff) {
return ValueDate.fromDateValue(DataUtils.readVarLong(buff));
}
};
}
|
int y = DateTimeUtils.yearFromDateValue(dateValue);
int m = DateTimeUtils.monthFromDateValue(dateValue);
int d = DateTimeUtils.dayFromDateValue(dateValue);
if (y > 0 && y < 10000) {
StringUtils.appendZeroPadded(buff, 4, y);
} else {
buff.append(y);
}
buff.append('-');
StringUtils.appendZeroPadded(buff, 2, m);
buff.append('-');
StringUtils.appendZeroPadded(buff, 2, d);
| 1,167
| 151
| 1,318
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueDouble.java
|
ValueDouble
|
get
|
class ValueDouble extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 17;
/**
* The maximum display size of a double.
* Example: -3.3333333333333334E-100
*/
public static final int DISPLAY_SIZE = 24;
/**
* Double.doubleToLongBits(0.0)
*/
public static final long ZERO_BITS = Double.doubleToLongBits(0.0);
private static final ValueDouble ZERO = new ValueDouble(0.0);
private static final ValueDouble ONE = new ValueDouble(1.0);
private static final ValueDouble NAN = new ValueDouble(Double.NaN);
private final double value;
private ValueDouble(double value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value + v2.value);
}
@Override
public Value subtract(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value - v2.value);
}
@Override
public Value negate() {
return ValueDouble.get(-value);
}
@Override
public Value multiply(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value * v2.value);
}
@Override
public Value divide(Value v) {
ValueDouble v2 = (ValueDouble) v;
if (v2.value == 0.0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueDouble.get(value / v2.value);
}
@Override
public ValueDouble modulus(Value v) {
ValueDouble other = (ValueDouble) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueDouble.get(value % other.value);
}
@Override
public String getSQL() {
if (value == Double.POSITIVE_INFINITY) {
return "POWER(0, -1)";
} else if (value == Double.NEGATIVE_INFINITY) {
return "(-POWER(0, -1))";
} else if (Double.isNaN(value)) {
return "SQRT(-1)";
}
String s = getString();
if (s.equals("-0.0")) {
return "-CAST(0 AS DOUBLE)";
}
return s;
}
@Override
public int getType() {
return Value.DOUBLE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueDouble v = (ValueDouble) o;
return Double.compare(value, v.value);
}
@Override
public int getSignum() {
return value == 0 ? 0 : (value < 0 ? -1 : 1);
}
@Override
public double getDouble() {
return value;
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getScale() {
return 0;
}
@Override
public int hashCode() {
long hash = Double.doubleToLongBits(value);
return (int) (hash ^ (hash >> 32));
}
@Override
public Object getObject() {
return Double.valueOf(value);
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setDouble(parameterIndex, value);
}
/**
* Get or create double value for the given double.
*
* @param d the double
* @return the value
*/
public static ValueDouble get(double d) {<FILL_FUNCTION_BODY>}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueDouble)) {
return false;
}
return compareSecure((ValueDouble) other, null) == 0;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return DOUBLE;
}
@Override
public int compare(Object aObj, Object bObj) {
Double a = (Double) aObj;
Double b = (Double) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 24;
}
@Override
public void write(DataBuffer buff, Object obj) {
double x = (Double) obj;
write0(buff, x);
}
@Override
public void writeValue(DataBuffer buff, Value v) {
double x = v.getDouble();
write0(buff, x);
}
private void write0(DataBuffer buff, double x) {
long d = Double.doubleToLongBits(x);
if (d == DOUBLE_ZERO_BITS) {
buff.put((byte) TAG_DOUBLE_0);
} else if (d == DOUBLE_ONE_BITS) {
buff.put((byte) TAG_DOUBLE_1);
} else {
long value = Long.reverse(d);
if (value >= 0 && value <= DataUtils.COMPRESSED_VAR_LONG_MAX) {
buff.put((byte) DOUBLE);
buff.putVarLong(value);
} else {
buff.put((byte) TAG_DOUBLE_FIXED);
buff.putDouble(x);
}
}
}
@Override
public Value readValue(ByteBuffer buff, int tag) {
switch (tag) {
case TAG_DOUBLE_0:
return ValueDouble.get(0d);
case TAG_DOUBLE_1:
return ValueDouble.get(1d);
case TAG_DOUBLE_FIXED:
return ValueDouble.get(buff.getDouble());
}
return ValueDouble.get(Double.longBitsToDouble(Long.reverse(DataUtils.readVarLong(buff))));
}
};
}
|
if (d == 1.0) {
return ONE;
} else if (d == 0.0) {
// unfortunately, -0.0 == 0.0, but we don't want to return
// 0.0 in this case
if (Double.doubleToLongBits(d) == ZERO_BITS) {
return ZERO;
}
} else if (Double.isNaN(d)) {
return NAN;
}
return (ValueDouble) Value.cache(new ValueDouble(d));
| 1,751
| 139
| 1,890
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueEnum.java
|
ValueEnum
|
multiply
|
class ValueEnum extends Value {
private String label;
private final int value;
private ValueEnum(String label, int value) {
this.label = label;
this.value = value;
}
private ValueEnum(int value) {
this.label = null;
this.value = value;
}
public static ValueEnum get(int ordinal) {
return new ValueEnum(null, ordinal);
}
public static ValueEnum get(String label, int ordinal) {
return new ValueEnum(label, ordinal);
}
@Override
public int getType() {
return Value.ENUM;
}
@Override
public Value add(Value v) {
ValueEnum other = (ValueEnum) v;
return checkRange(value + (long) other.value);
}
private static ValueEnum checkRange(long x) {
if (x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) {
throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, Long.toString(x));
}
return ValueEnum.get((int) x);
}
@Override
public int getSignum() {
return Integer.signum(value);
}
@Override
public Value negate() {
return checkRange(-(long) value);
}
@Override
public Value subtract(Value v) {
ValueEnum other = (ValueEnum) v;
return checkRange(value - (long) other.value);
}
@Override
public Value multiply(Value v) {<FILL_FUNCTION_BODY>}
@Override
public Value divide(Value v) {
ValueEnum other = (ValueEnum) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueEnum.get(value / other.value);
}
@Override
public Value modulus(Value v) {
ValueEnum other = (ValueEnum) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueEnum.get(value % other.value);
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getInt() {
return value;
}
@Override
public long getLong() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueEnum v = (ValueEnum) o;
if (label != null && v.label != null)
return mode.compareString(label, v.label, false);
return MathUtils.compareInt(value, v.value);
}
@Override
public String getString() {
return label;
}
@Override
public long getPrecision() {
return ValueInt.PRECISION;
}
@Override
public int getDisplaySize() {
return ValueInt.DISPLAY_SIZE;
}
@Override
public int hashCode() {
return value;
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setInt(parameterIndex, value);
}
@Override
public boolean equals(Object other) {
return other instanceof ValueEnum && value == ((ValueEnum) other).value;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
|
ValueEnum other = (ValueEnum) v;
return checkRange(value * (long) other.value);
| 986
| 30
| 1,016
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueFloat.java
|
ValueFloat
|
compare
|
class ValueFloat extends Value {
/**
* Float.floatToIntBits(0.0F).
*/
public static final int ZERO_BITS = Float.floatToIntBits(0.0F);
/**
* The precision in digits.
*/
static final int PRECISION = 7;
/**
* The maximum display size of a float.
* Example: -1.12345676E-20
*/
static final int DISPLAY_SIZE = 15;
private static final ValueFloat ZERO = new ValueFloat(0.0F);
private static final ValueFloat ONE = new ValueFloat(1.0F);
private final float value;
private ValueFloat(float value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueFloat v2 = (ValueFloat) v;
return ValueFloat.get(value + v2.value);
}
@Override
public Value subtract(Value v) {
ValueFloat v2 = (ValueFloat) v;
return ValueFloat.get(value - v2.value);
}
@Override
public Value negate() {
return ValueFloat.get(-value);
}
@Override
public Value multiply(Value v) {
ValueFloat v2 = (ValueFloat) v;
return ValueFloat.get(value * v2.value);
}
@Override
public Value divide(Value v) {
ValueFloat v2 = (ValueFloat) v;
if (v2.value == 0.0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueFloat.get(value / v2.value);
}
@Override
public Value modulus(Value v) {
ValueFloat other = (ValueFloat) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueFloat.get(value % other.value);
}
@Override
public String getSQL() {
if (value == Float.POSITIVE_INFINITY) {
return "POWER(0, -1)";
} else if (value == Float.NEGATIVE_INFINITY) {
return "(-POWER(0, -1))";
} else if (Double.isNaN(value)) {
// NaN
return "SQRT(-1)";
}
String s = getString();
if (s.equals("-0.0")) {
return "-CAST(0 AS REAL)";
}
return s;
}
@Override
public int getType() {
return Value.FLOAT;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueFloat v = (ValueFloat) o;
return Float.compare(value, v.value);
}
@Override
public int getSignum() {
return value == 0 ? 0 : (value < 0 ? -1 : 1);
}
@Override
public float getFloat() {
return value;
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getScale() {
return 0;
}
@Override
public int hashCode() {
long hash = Float.floatToIntBits(value);
return (int) (hash ^ (hash >> 32));
}
@Override
public Object getObject() {
return Float.valueOf(value);
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setFloat(parameterIndex, value);
}
/**
* Get or create float value for the given float.
*
* @param d the float
* @return the value
*/
public static ValueFloat get(float d) {
if (d == 1.0F) {
return ONE;
} else if (d == 0.0F) {
// unfortunately, -0.0 == 0.0, but we don't want to return
// 0.0 in this case
if (Float.floatToIntBits(d) == ZERO_BITS) {
return ZERO;
}
}
return (ValueFloat) Value.cache(new ValueFloat(d));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueFloat)) {
return false;
}
return compareSecure((ValueFloat) other, null) == 0;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return FLOAT;
}
@Override
public int compare(Object aObj, Object bObj) {<FILL_FUNCTION_BODY>}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
float x = (Float) obj;
write0(buff, x);
}
@Override
public void writeValue(DataBuffer buff, Value v) {
float x = v.getFloat();
write0(buff, x);
}
private void write0(DataBuffer buff, float x) {
int f = Float.floatToIntBits(x);
if (f == FLOAT_ZERO_BITS) {
buff.put((byte) TAG_FLOAT_0);
} else if (f == FLOAT_ONE_BITS) {
buff.put((byte) TAG_FLOAT_1);
} else {
int value = Integer.reverse(f);
if (value >= 0 && value <= DataUtils.COMPRESSED_VAR_INT_MAX) {
buff.put((byte) FLOAT).putVarInt(value);
} else {
buff.put((byte) TAG_FLOAT_FIXED).putFloat(x);
}
}
}
@Override
public Value readValue(ByteBuffer buff, int tag) {
switch (tag) {
case TAG_FLOAT_0:
return ValueFloat.get(0f);
case TAG_FLOAT_1:
return ValueFloat.get(1f);
case TAG_FLOAT_FIXED:
return ValueFloat.get(buff.getFloat());
}
return ValueFloat.get(Float.intBitsToFloat(Integer.reverse(DataUtils.readVarInt(buff))));
}
};
}
|
Float a = (Float) aObj;
Float b = (Float) bObj;
return a.compareTo(b);
| 1,811
| 37
| 1,848
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueInt.java
|
ValueInt
|
write0
|
class ValueInt extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 10;
/**
* The maximum display size of an int.
* Example: -2147483648
*/
public static final int DISPLAY_SIZE = 11;
private static final int STATIC_SIZE = 128;
// must be a power of 2
private static final int DYNAMIC_SIZE = 256;
private static final ValueInt[] STATIC_CACHE = new ValueInt[STATIC_SIZE];
private static final ValueInt[] DYNAMIC_CACHE = new ValueInt[DYNAMIC_SIZE];
private final int value;
static {
for (int i = 0; i < STATIC_SIZE; i++) {
STATIC_CACHE[i] = new ValueInt(i);
}
}
private ValueInt(int value) {
this.value = value;
}
/**
* Get or create an int value for the given int.
*
* @param i the int
* @return the value
*/
public static ValueInt get(int i) {
if (i >= 0 && i < STATIC_SIZE) {
return STATIC_CACHE[i];
}
ValueInt v = DYNAMIC_CACHE[i & (DYNAMIC_SIZE - 1)];
if (v == null || v.value != i) {
v = new ValueInt(i);
DYNAMIC_CACHE[i & (DYNAMIC_SIZE - 1)] = v;
}
return v;
}
@Override
public Value add(Value v) {
ValueInt other = (ValueInt) v;
return checkRange((long) value + (long) other.value);
}
private static ValueInt checkRange(long x) {
if (x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) {
throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, Long.toString(x));
}
return ValueInt.get((int) x);
}
@Override
public int getSignum() {
return Integer.signum(value);
}
@Override
public Value negate() {
return checkRange(-(long) value);
}
@Override
public Value subtract(Value v) {
ValueInt other = (ValueInt) v;
return checkRange((long) value - (long) other.value);
}
@Override
public Value multiply(Value v) {
ValueInt other = (ValueInt) v;
return checkRange((long) value * (long) other.value);
}
@Override
public Value divide(Value v) {
ValueInt other = (ValueInt) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueInt.get(value / other.value);
}
@Override
public Value modulus(Value v) {
ValueInt other = (ValueInt) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueInt.get(value % other.value);
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.INT;
}
@Override
public int getInt() {
return value;
}
@Override
public long getLong() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueInt v = (ValueInt) o;
return MathUtils.compareInt(value, v.value);
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value;
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setInt(parameterIndex, value);
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueInt && value == ((ValueInt) other).value;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return INT;
}
@Override
public int compare(Object aObj, Object bObj) {
Integer a = (Integer) aObj;
Integer b = (Integer) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
int x = (Integer) obj;
write0(buff, x);
}
@Override
public void writeValue(DataBuffer buff, Value v) {
int x = v.getInt();
write0(buff, x);
}
private void write0(DataBuffer buff, int x) {<FILL_FUNCTION_BODY>}
@Override
public Value readValue(ByteBuffer buff, int tag) {
switch (tag) {
case INT:
return ValueInt.get(DataUtils.readVarInt(buff));
case TAG_INTEGER_NEGATIVE:
return ValueInt.get(-DataUtils.readVarInt(buff));
case TAG_INTEGER_FIXED:
return ValueInt.get(buff.getInt());
}
return ValueInt.get(tag - TAG_INTEGER_0_15);
}
};
}
|
if (x < 0) {
// -Integer.MIN_VALUE is smaller than 0
if (-x < 0 || -x > DataUtils.COMPRESSED_VAR_INT_MAX) {
buff.put((byte) TAG_INTEGER_FIXED).putInt(x);
} else {
buff.put((byte) TAG_INTEGER_NEGATIVE).putVarInt(-x);
}
} else if (x <= 15) {
buff.put((byte) (TAG_INTEGER_0_15 + x));
} else if (x <= DataUtils.COMPRESSED_VAR_INT_MAX) {
buff.put((byte) INT).putVarInt(x);
} else {
buff.put((byte) TAG_INTEGER_FIXED).putInt(x);
}
| 1,605
| 211
| 1,816
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueJavaObject.java
|
NotSerialized
|
compareSecure
|
class NotSerialized extends ValueJavaObject {
private Object javaObject;
private int displaySize = -1;
NotSerialized(Object javaObject, byte[] v) {
super(v);
this.javaObject = javaObject;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setObject(parameterIndex, getObject(), Types.JAVA_OBJECT);
}
@Override
public byte[] getBytesNoCopy() {
if (value == null) {
value = Utils.serialize(javaObject);
}
return value;
}
@Override
protected int compareSecure(Value v, CompareMode mode) {<FILL_FUNCTION_BODY>}
@Override
public String getString() {
String str = getObject().toString();
if (displaySize == -1) {
displaySize = str.length();
}
return str;
}
@Override
public long getPrecision() {
return 0;
}
@Override
public int hashCode() {
if (hash == 0) {
hash = getObject().hashCode();
}
return hash;
}
@Override
public Object getObject() {
if (javaObject == null) {
javaObject = Utils.deserialize(value);
}
return javaObject;
}
@Override
public int getDisplaySize() {
if (displaySize == -1) {
displaySize = getString().length();
}
return displaySize;
}
@Override
public int getMemory() {
if (value == null) {
return DataType.getDataType(getType()).memory;
}
int mem = super.getMemory();
if (javaObject != null) {
mem *= 2;
}
return mem;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof NotSerialized)) {
return false;
}
return getObject().equals(((NotSerialized) other).getObject());
}
@Override
public Value convertPrecision(long precision, boolean force) {
return this;
}
}
|
Object o1 = getObject();
Object o2 = v.getObject();
boolean o1Comparable = o1 instanceof Comparable;
boolean o2Comparable = o2 instanceof Comparable;
if (o1Comparable && o2Comparable
&& Utils.haveCommonComparableSuperclass(o1.getClass(), o2.getClass())) {
@SuppressWarnings("unchecked")
Comparable<Object> c1 = (Comparable<Object>) o1;
return c1.compareTo(o2);
}
// group by types
if (o1.getClass() != o2.getClass()) {
if (o1Comparable != o2Comparable) {
return o1Comparable ? -1 : 1;
}
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
// compare hash codes
int h1 = hashCode();
int h2 = v.hashCode();
if (h1 == h2) {
if (o1.equals(o2)) {
return 0;
}
return Utils.compareNotNullSigned(getBytesNoCopy(), v.getBytesNoCopy());
}
return h1 > h2 ? 1 : -1;
| 579
| 339
| 918
|
<methods>public com.lealone.db.value.Value convertPrecision(long, boolean) ,public boolean equals(java.lang.Object) ,public static com.lealone.db.value.ValueBytes get(byte[]) ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public int getDisplaySize() ,public int getMemory() ,public static com.lealone.db.value.ValueBytes getNoCopy(byte[]) ,public java.lang.Object getObject() ,public long getPrecision() ,public java.lang.String getSQL() ,public java.lang.String getString() ,public int getType() ,public int hashCode() ,public void set(java.sql.PreparedStatement, int) throws java.sql.SQLException<variables>private static final com.lealone.db.value.ValueBytes EMPTY,protected int hash,protected byte[] value
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueList.java
|
ValueList
|
convertPrecision
|
class ValueList extends Value {
private final Class<?> componentType;
private final List<Value> values;
private int hash;
private ValueList(Class<?> componentType, List<?> list) {
this.componentType = componentType;
this.values = new ArrayList<>(list.size());
int type = getCollectionComponentTypeFromClass(componentType);
for (Object v : list) {
values.add(DataType.convertToValue(v, type));
}
}
private ValueList(Class<?> componentType, Value[] values) {
this.componentType = componentType;
this.values = new ArrayList<>(values.length);
for (Value v : values) {
this.values.add(v);
}
}
public static ValueList get(Value[] values) {
return new ValueList(Object.class, values);
}
public static ValueList get(Class<?> componentType, Value[] values) {
return new ValueList(componentType, values);
}
public static ValueList get(List<?> list) {
return new ValueList(Object.class, list);
}
public static ValueList get(Class<?> componentType, List<?> list) {
return new ValueList(componentType, list);
}
@Override
public int hashCode() {
if (hash != 0) {
return hash;
}
int h = 1;
for (Value v : values) {
h = h * 31 + v.hashCode();
}
hash = h;
return h;
}
public List<Value> getList() {
return values;
}
@Override
public int getType() {
return Value.LIST;
}
public Class<?> getComponentType() {
return componentType;
}
@Override
public long getPrecision() {
long p = 0;
for (Value v : values) {
p += v.getPrecision();
}
return p;
}
@Override
public String getString() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getString());
}
return buff.append(')').toString();
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueList v = (ValueList) o;
if (values == v.values) {
return 0;
}
int l = values.size();
int ol = v.values.size();
int len = Math.min(l, ol);
for (int i = 0; i < len; i++) {
Value v1 = values.get(i);
Value v2 = v.values.get(i);
int comp = v1.compareTo(v2, mode);
if (comp != 0) {
return comp;
}
}
return l > ol ? 1 : l == ol ? 0 : -1;
}
@Override
public Object getObject() {
int len = values.size();
Object[] list = (Object[]) Array.newInstance(componentType, len);
for (int i = 0; i < len; i++) {
list[i] = values.get(i).getObject();
}
return Arrays.asList(list);
}
@Override
public void set(PreparedStatement prep, int parameterIndex) {
throw throwUnsupportedExceptionForType("PreparedStatement.set");
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getSQL());
}
if (values.size() == 1) {
buff.append(',');
}
return buff.append(')').toString();
}
@Override
public String getTraceSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getTraceSQL());
}
return buff.append(')').toString();
}
@Override
public int getDisplaySize() {
long size = 0;
for (Value v : values) {
size += v.getDisplaySize();
}
return MathUtils.convertLongToInt(size);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueList)) {
return false;
}
ValueList v = (ValueList) other;
if (values == v.values) {
return true;
}
int len = values.size();
if (len != v.values.size()) {
return false;
}
for (int i = 0; i < len; i++) {
if (!values.get(i).equals(v.values.get(i))) {
return false;
}
}
return true;
}
@Override
public int getMemory() {
int memory = 32;
for (Value v : values) {
memory += v.getMemory() + Constants.MEMORY_POINTER;
}
return memory;
}
@Override
public Value convertPrecision(long precision, boolean force) {<FILL_FUNCTION_BODY>}
public Value getValue(int i) {
return values.get(i);
}
@Override
public Value add(Value v) {
ValueList vl = (ValueList) v;
List<Value> newValues = new ArrayList<>(values.size() + vl.values.size());
newValues.addAll(values);
newValues.addAll(vl.values);
return ValueList.get(componentType, newValues);
}
@Override
public Value subtract(Value v) {
ValueList vl = (ValueList) v;
List<Value> newValues = new ArrayList<>(Math.abs(values.size() - vl.values.size()));
newValues.addAll(values);
newValues.removeAll(vl.values);
return ValueList.get(componentType, newValues);
}
public void convertComponent(int type) {
for (int i = 0, size = values.size(); i < size; i++) {
values.set(i, values.get(i).convertTo(type));
}
}
}
|
if (!force) {
return this;
}
int length = values.size();
Value[] newValues = new Value[length];
int i = 0;
boolean modified = false;
for (; i < length; i++) {
Value old = values.get(i);
Value v = old.convertPrecision(precision, true);
if (v != old) {
modified = true;
}
// empty byte arrays or strings have precision 0
// they count as precision 1 here
precision -= Math.max(1, v.getPrecision());
if (precision < 0) {
break;
}
newValues[i] = v;
}
if (i < length) {
return get(componentType, Arrays.asList(Arrays.copyOf(newValues, i)));
}
return modified ? get(componentType, Arrays.asList(newValues)) : this;
| 1,688
| 239
| 1,927
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueNull.java
|
ValueNull
|
compare
|
class ValueNull extends Value {
/**
* The main NULL instance.
*/
public static final ValueNull INSTANCE = new ValueNull();
/**
* This special instance is used as a marker for deleted entries in a map.
* It should not be used anywhere else.
*/
public static final ValueNull DELETED = new ValueNull();
/**
* The precision of NULL.
*/
private static final int PRECISION = 1;
/**
* The display size of the textual representation of NULL.
*/
private static final int DISPLAY_SIZE = 4;
private ValueNull() {
// don't allow construction
}
@Override
public String getSQL() {
return "NULL";
}
@Override
public int getType() {
return Value.NULL;
}
@Override
public String getString() {
return null;
}
@Override
public boolean getBoolean() {
return false;
}
@Override
public Date getDate() {
return null;
}
@Override
public Time getTime() {
return null;
}
@Override
public Timestamp getTimestamp() {
return null;
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public byte getByte() {
return 0;
}
@Override
public short getShort() {
return 0;
}
@Override
public BigDecimal getBigDecimal() {
return null;
}
@Override
public double getDouble() {
return 0.0;
}
@Override
public float getFloat() {
return 0.0F;
}
@Override
public int getInt() {
return 0;
}
@Override
public long getLong() {
return 0;
}
@Override
public InputStream getInputStream() {
return null;
}
@Override
public Reader getReader() {
return null;
}
@Override
public Value convertTo(int type) {
return this;
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
throw DbException.getInternalError("compare null");
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return 0;
}
@Override
public Object getObject() {
return null;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setNull(parameterIndex, DataType.convertTypeToSQLType(Value.NULL));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other == this;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return NULL;
}
@Override
public int compare(Object aObj, Object bObj) {<FILL_FUNCTION_BODY>}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
buff.put((byte) Value.NULL);
}
@Override
public void writeValue(DataBuffer buff, Value v) {
buff.put((byte) Value.NULL);
}
@Override
public Value readValue(ByteBuffer buff) {
return ValueNull.INSTANCE;
}
};
}
|
if (aObj == null && bObj == null) {
return 0;
} else if (aObj == null) {
return -1;
} else {
return 1;
}
| 983
| 56
| 1,039
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueResultSet.java
|
ValueResultSet
|
getCopy
|
class ValueResultSet extends Value {
private final ResultSet result;
private ValueResultSet(ResultSet rs) {
this.result = rs;
}
/**
* Create a result set value for the given result set.
* The result set will be wrapped.
*
* @param rs the result set
* @return the value
*/
public static ValueResultSet get(ResultSet rs) {
ValueResultSet val = new ValueResultSet(rs);
return val;
}
/**
* Create a result set value for the given result set. The result set will
* be fully read in memory. The original result set is not closed.
*
* @param rs the result set
* @param maxRows the maximum number of rows to read (0 to just read the
* meta data)
* @return the value
*/
public static ValueResultSet getCopy(ResultSet rs, int maxRows) {<FILL_FUNCTION_BODY>}
@Override
public int getType() {
return Value.RESULT_SET;
}
@Override
public long getPrecision() {
return Integer.MAX_VALUE;
}
@Override
public int getDisplaySize() {
// it doesn't make sense to calculate it
return Integer.MAX_VALUE;
}
@Override
public String getString() {
try {
StatementBuilder buff = new StatementBuilder("(");
result.beforeFirst();
ResultSetMetaData meta = result.getMetaData();
int columnCount = meta.getColumnCount();
for (int i = 0; result.next(); i++) {
if (i > 0) {
buff.append(", ");
}
buff.append('(');
buff.resetCount();
for (int j = 0; j < columnCount; j++) {
buff.appendExceptFirst(", ");
int t = DataType.convertSQLTypeToValueType(meta.getColumnType(j + 1));
Value v = DataType.readValue(null, result, j + 1, t);
buff.append(v.getString());
}
buff.append(')');
}
result.beforeFirst();
return buff.append(')').toString();
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
return this == v ? 0 : super.toString().compareTo(v.toString());
}
@Override
public boolean equals(Object other) {
return other == this;
}
@Override
public int hashCode() {
return 0;
}
@Override
public Object getObject() {
return result;
}
@Override
public ResultSet getResultSet() {
return result;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) {
throw throwUnsupportedExceptionForType("PreparedStatement.set");
}
@Override
public String getSQL() {
return "";
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (!force) {
return this;
}
return ValueResultSet.get(new SimpleResultSet());
}
}
|
try {
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
SimpleResultSet simple = new SimpleResultSet();
simple.setAutoClose(false);
ValueResultSet val = new ValueResultSet(simple);
for (int i = 0; i < columnCount; i++) {
String name = meta.getColumnLabel(i + 1);
int sqlType = meta.getColumnType(i + 1);
int precision = meta.getPrecision(i + 1);
int scale = meta.getScale(i + 1);
simple.addColumn(name, sqlType, precision, scale);
}
for (int i = 0; i < maxRows && rs.next(); i++) {
Object[] list = new Object[columnCount];
for (int j = 0; j < columnCount; j++) {
list[j] = rs.getObject(j + 1);
}
simple.addRow(list);
}
return val;
} catch (SQLException e) {
throw DbException.convert(e);
}
| 853
| 281
| 1,134
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueSet.java
|
ValueSet
|
compareSecure
|
class ValueSet extends Value {
private final Class<?> componentType;
private final Set<Value> values;
private int hash;
private ValueSet(Class<?> componentType, Set<?> set) {
this.componentType = componentType;
this.values = new HashSet<>(set.size());
int type = getCollectionComponentTypeFromClass(componentType);
for (Object v : set) {
values.add(DataType.convertToValue(v, type));
}
}
private ValueSet(Class<?> componentType, Value[] values) {
this.componentType = componentType;
this.values = new HashSet<>(values.length);
for (Value v : values) {
this.values.add(v);
}
}
public static ValueSet get(Value[] values) {
return new ValueSet(Object.class, values);
}
public static ValueSet get(Class<?> componentType, Value[] values) {
return new ValueSet(componentType, values);
}
public static ValueSet get(Set<?> set) {
return new ValueSet(Object.class, set);
}
public static ValueSet get(Class<?> componentType, Set<?> set) {
return new ValueSet(componentType, set);
}
@Override
public int hashCode() {
if (hash != 0) {
return hash;
}
int h = 1;
for (Value v : values) {
h = h * 31 + v.hashCode();
}
hash = h;
return h;
}
public Set<Value> getSet() {
return values;
}
@Override
public int getType() {
return Value.SET;
}
public Class<?> getComponentType() {
return componentType;
}
@Override
public long getPrecision() {
long p = 0;
for (Value v : values) {
p += v.getPrecision();
}
return p;
}
@Override
public String getString() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getString());
}
return buff.append(')').toString();
}
@Override
protected int compareSecure(Value o, CompareMode mode) {<FILL_FUNCTION_BODY>}
@Override
public Object getObject() {
HashSet<Object> set = new HashSet<>(values.size());
for (Value v : values) {
set.add(v.getObject());
}
return set;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) {
throw throwUnsupportedExceptionForType("PreparedStatement.set");
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getSQL());
}
if (values.size() == 1) {
buff.append(',');
}
return buff.append(')').toString();
}
@Override
public String getTraceSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getTraceSQL());
}
return buff.append(')').toString();
}
@Override
public int getDisplaySize() {
long size = 0;
for (Value v : values) {
size += v.getDisplaySize();
}
return MathUtils.convertLongToInt(size);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueSet)) {
return false;
}
ValueSet v = (ValueSet) other;
if (values == v.values) {
return true;
}
int len = values.size();
if (len != v.values.size()) {
return false;
}
return values.equals(v.values);
}
@Override
public int getMemory() {
int memory = 32;
for (Value v : values) {
memory += v.getMemory() + Constants.MEMORY_POINTER;
}
return memory;
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (!force) {
return this;
}
int length = values.size();
Value[] newValues = new Value[length];
int i = 0;
boolean modified = false;
for (Value old : values) {
Value v = old.convertPrecision(precision, true);
if (v != old) {
modified = true;
}
// empty byte arrays or strings have precision 0
// they count as precision 1 here
precision -= Math.max(1, v.getPrecision());
if (precision < 0) {
break;
}
newValues[i] = v;
}
if (i < length) {
return get(componentType, new HashSet<>(Arrays.asList(Arrays.copyOf(newValues, i))));
}
return modified ? get(componentType, new HashSet<>(Arrays.asList(newValues))) : this;
}
@Override
public Value add(Value v) {
ValueSet vs = (ValueSet) v;
Set<Value> newValues = new HashSet<>(values.size() + vs.values.size());
newValues.addAll(values);
newValues.addAll(vs.values);
return ValueSet.get(componentType, newValues);
}
@Override
public Value subtract(Value v) {
ValueSet vs = (ValueSet) v;
Set<Value> newValues = new HashSet<>(Math.abs(values.size() - vs.values.size()));
newValues.addAll(values);
newValues.removeAll(vs.values);
return ValueSet.get(componentType, newValues);
}
public void convertComponent(int type) {
Set<Value> newValues = new HashSet<>(values.size());
for (Value v : values) {
newValues.add(v.convertTo(type));
}
values.clear();
values.addAll(newValues);
}
}
|
ValueSet v = (ValueSet) o;
if (values == v.values) {
return 0;
}
int l = values.size();
int ol = v.values.size();
int len = Math.min(l, ol);
for (int i = 0; i < len; i++) {
// Value v1 = values.get(i);
// Value v2 = v.values.get(i);
// int comp = v1.compareTo(v2, mode);
// if (comp != 0) {
// return comp;
// }
}
return l > ol ? 1 : l == ol ? 0 : -1;
| 1,675
| 174
| 1,849
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueShort.java
|
ValueShort
|
checkRange
|
class ValueShort extends Value {
/**
* The precision in digits.
*/
static final int PRECISION = 5;
/**
* The maximum display size of a short.
* Example: -32768
*/
static final int DISPLAY_SIZE = 6;
private final short value;
private ValueShort(short value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueShort other = (ValueShort) v;
return checkRange(value + other.value);
}
private static ValueShort checkRange(int x) {<FILL_FUNCTION_BODY>}
@Override
public int getSignum() {
return Integer.signum(value);
}
@Override
public Value negate() {
return checkRange(-(int) value);
}
@Override
public Value subtract(Value v) {
ValueShort other = (ValueShort) v;
return checkRange(value - other.value);
}
@Override
public Value multiply(Value v) {
ValueShort other = (ValueShort) v;
return checkRange(value * other.value);
}
@Override
public Value divide(Value v) {
ValueShort other = (ValueShort) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueShort.get((short) (value / other.value));
}
@Override
public Value modulus(Value v) {
ValueShort other = (ValueShort) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueShort.get((short) (value % other.value));
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.SHORT;
}
@Override
public short getShort() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueShort v = (ValueShort) o;
return MathUtils.compareInt(value, v.value);
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value;
}
@Override
public Object getObject() {
return Short.valueOf(value);
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setShort(parameterIndex, value);
}
/**
* Get or create a short value for the given short.
*
* @param i the short
* @return the value
*/
public static ValueShort get(short i) {
return (ValueShort) Value.cache(new ValueShort(i));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueShort && value == ((ValueShort) other).value;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return SHORT;
}
@Override
public int compare(Object aObj, Object bObj) {
Short a = (Short) aObj;
Short b = (Short) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
buff.put((byte) Value.SHORT).putShort(((Short) obj).shortValue());
}
@Override
public void writeValue(DataBuffer buff, Value v) {
buff.put((byte) Value.SHORT).putShort(v.getShort());
}
@Override
public Value readValue(ByteBuffer buff) {
return ValueShort.get(buff.getShort());
}
};
}
|
if (x < Short.MIN_VALUE || x > Short.MAX_VALUE) {
throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, Integer.toString(x));
}
return ValueShort.get((short) x);
| 1,135
| 72
| 1,207
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueString.java
|
StringDataType
|
write0
|
class StringDataType extends StorageDataTypeBase {
private StringDataType() {
}
@Override
public int getType() {
return STRING;
}
@Override
public int compare(Object aObj, Object bObj) {
return aObj.toString().compareTo(bObj.toString());
}
@Override
public int getMemory(Object obj) {
return 16 + 2 * obj.toString().length();
}
@Override
public void write(DataBuffer buff, Object obj) {
String s = (String) obj;
write0(buff, s);
}
@Override
public void writeValue(DataBuffer buff, Value v) {
String s = v.getString();
write0(buff, s);
}
private void write0(DataBuffer buff, String s) {<FILL_FUNCTION_BODY>}
@Override
public String read(ByteBuffer buff) {
return (String) super.read(buff);
}
@Override
public Value readValue(ByteBuffer buff, int tag) {
int len;
if (tag == STRING) {
len = DataUtils.readVarInt(buff);
if (len == 0)
return ValueNull.INSTANCE;
} else {
len = tag - TAG_STRING_0_15;
}
return ValueString.get(DataUtils.readString(buff, len));
}
}
|
if (s == null) {
buff.put((byte) STRING).putVarInt((byte) 0);
return;
}
int len = s.length();
if (len <= 15) {
buff.put((byte) (TAG_STRING_0_15 + len));
} else {
buff.put((byte) STRING).putVarInt(len);
}
buff.putStringData(s, len);
| 372
| 115
| 487
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueStringFixed.java
|
ValueStringFixed
|
get
|
class ValueStringFixed extends ValueString {
private static final ValueStringFixed EMPTY = new ValueStringFixed("");
protected ValueStringFixed(String value) {
super(value);
}
private static String trimRight(String s) {
int endIndex = s.length() - 1;
int i = endIndex;
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
s = i == endIndex ? s : s.substring(0, i + 1);
return s;
}
@Override
public int getType() {
return Value.STRING_FIXED;
}
/**
* Get or create a fixed length string value for the given string.
* Spaces at the end of the string will be removed.
*
* @param s the string
* @return the value
*/
public static ValueStringFixed get(String s) {<FILL_FUNCTION_BODY>}
@Override
protected ValueString getNew(String s) {
return ValueStringFixed.get(s);
}
}
|
s = trimRight(s);
if (s.length() == 0) {
return EMPTY;
}
ValueStringFixed obj = new ValueStringFixed(StringUtils.cache(s));
if (s.length() > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
return (ValueStringFixed) Value.cache(obj);
| 282
| 105
| 387
|
<methods>public com.lealone.db.value.Value convertPrecision(long, boolean) ,public boolean equals(java.lang.Object) ,public static com.lealone.db.value.ValueString get(java.lang.String) ,public static com.lealone.db.value.Value get(java.lang.String, boolean) ,public int getDisplaySize() ,public int getMemory() ,public java.lang.Object getObject() ,public long getPrecision() ,public java.lang.String getSQL() ,public java.lang.String getString() ,public int getType() ,public int hashCode() ,public void set(java.sql.PreparedStatement, int) throws java.sql.SQLException<variables>private static final com.lealone.db.value.ValueString EMPTY,public static final com.lealone.db.value.ValueString.StringDataType type,protected final non-sealed java.lang.String value
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueStringIgnoreCase.java
|
ValueStringIgnoreCase
|
get
|
class ValueStringIgnoreCase extends ValueString {
private static final ValueStringIgnoreCase EMPTY = new ValueStringIgnoreCase("");
private int hash;
protected ValueStringIgnoreCase(String value) {
super(value);
}
@Override
public int getType() {
return Value.STRING_IGNORECASE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueStringIgnoreCase v = (ValueStringIgnoreCase) o;
return mode.compareString(value, v.value, true);
}
@Override
public boolean equals(Object other) {
return other instanceof ValueString && value.equalsIgnoreCase(((ValueString) other).value);
}
@Override
public int hashCode() {
if (hash == 0) {
// this is locale sensitive
hash = value.toUpperCase().hashCode();
}
return hash;
}
@Override
public String getSQL() {
return "CAST(" + StringUtils.quoteStringSQL(value) + " AS VARCHAR_IGNORECASE)";
}
/**
* Get or create a case insensitive string value for the given string.
* The value will have the same case as the passed string.
*
* @param s the string
* @return the value
*/
public static ValueStringIgnoreCase get(String s) {<FILL_FUNCTION_BODY>}
@Override
protected ValueString getNew(String s) {
return ValueStringIgnoreCase.get(s);
}
}
|
if (s.length() == 0) {
return EMPTY;
}
ValueStringIgnoreCase obj = new ValueStringIgnoreCase(StringUtils.cache(s));
if (s.length() > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
ValueStringIgnoreCase cache = (ValueStringIgnoreCase) Value.cache(obj);
// the cached object could have the wrong case
// (it would still be 'equal', but we don't like to store it)
if (cache.value.equals(s)) {
return cache;
}
return obj;
| 400
| 162
| 562
|
<methods>public com.lealone.db.value.Value convertPrecision(long, boolean) ,public boolean equals(java.lang.Object) ,public static com.lealone.db.value.ValueString get(java.lang.String) ,public static com.lealone.db.value.Value get(java.lang.String, boolean) ,public int getDisplaySize() ,public int getMemory() ,public java.lang.Object getObject() ,public long getPrecision() ,public java.lang.String getSQL() ,public java.lang.String getString() ,public int getType() ,public int hashCode() ,public void set(java.sql.PreparedStatement, int) throws java.sql.SQLException<variables>private static final com.lealone.db.value.ValueString EMPTY,public static final com.lealone.db.value.ValueString.StringDataType type,protected final non-sealed java.lang.String value
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueTime.java
|
ValueTime
|
writeValue
|
class ValueTime extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 6;
/**
* The display size of the textual representation of a time.
* Example: 10:00:00
*/
static final int DISPLAY_SIZE = 8;
private final long nanos;
private ValueTime(long nanos) {
this.nanos = nanos;
}
/**
* Get or create a time value.
*
* @param nanos the nanoseconds
* @return the value
*/
public static ValueTime fromNanos(long nanos) {
return (ValueTime) Value.cache(new ValueTime(nanos));
}
/**
* Get or create a time value for the given time.
*
* @param time the time
* @return the value
*/
public static ValueTime get(Time time) {
return fromNanos(DateTimeUtils.nanosFromDate(time.getTime()));
}
/**
* Parse a string to a ValueTime.
*
* @param s the string to parse
* @return the time
*/
public static ValueTime parse(String s) {
try {
return fromNanos(DateTimeUtils.parseTimeNanos(s, 0, s.length(), false));
} catch (Exception e) {
throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2, e, "TIME", s);
}
}
public long getNanos() {
return nanos;
}
@Override
public Time getTime() {
return DateTimeUtils.convertNanoToTime(nanos);
}
@Override
public int getType() {
return Value.TIME;
}
@Override
public String getString() {
StringBuilder buff = new StringBuilder(DISPLAY_SIZE);
appendTime(buff, nanos, false);
return buff.toString();
}
@Override
public String getSQL() {
return "TIME '" + getString() + "'";
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
return MathUtils.compareLong(nanos, ((ValueTime) o).nanos);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
return other instanceof ValueTime && nanos == (((ValueTime) other).nanos);
}
@Override
public int hashCode() {
return (int) (nanos ^ (nanos >>> 32));
}
@Override
public Object getObject() {
return getTime();
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setTime(parameterIndex, getTime());
}
@Override
public Value add(Value v) {
ValueTime t = (ValueTime) v.convertTo(Value.TIME);
return ValueTime.fromNanos(nanos + t.getNanos());
}
@Override
public Value subtract(Value v) {
ValueTime t = (ValueTime) v.convertTo(Value.TIME);
return ValueTime.fromNanos(nanos - t.getNanos());
}
@Override
public Value multiply(Value v) {
return ValueTime.fromNanos((long) (nanos * v.getDouble()));
}
@Override
public Value divide(Value v) {
return ValueTime.fromNanos((long) (nanos / v.getDouble()));
}
@Override
public int getSignum() {
return Long.signum(nanos);
}
@Override
public Value negate() {
return ValueTime.fromNanos(-nanos);
}
/**
* Append a time to the string builder.
*
* @param buff the target string builder
* @param nanos the time in nanoseconds
* @param alwaysAddMillis whether to always add at least ".0"
*/
static void appendTime(StringBuilder buff, long nanos, boolean alwaysAddMillis) {
if (nanos < 0) {
buff.append('-');
nanos = -nanos;
}
long ms = nanos / 1000000;
nanos -= ms * 1000000;
long s = ms / 1000;
ms -= s * 1000;
long m = s / 60;
s -= m * 60;
long h = m / 60;
m -= h * 60;
StringUtils.appendZeroPadded(buff, 2, h);
buff.append(':');
StringUtils.appendZeroPadded(buff, 2, m);
buff.append(':');
StringUtils.appendZeroPadded(buff, 2, s);
if (alwaysAddMillis || ms > 0 || nanos > 0) {
buff.append('.');
int start = buff.length();
StringUtils.appendZeroPadded(buff, 3, ms);
if (nanos > 0) {
StringUtils.appendZeroPadded(buff, 6, nanos);
}
for (int i = buff.length() - 1; i > start; i--) {
if (buff.charAt(i) != '0') {
break;
}
buff.deleteCharAt(i);
}
}
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return TIME;
}
@Override
public int compare(Object aObj, Object bObj) {
Time a = (Time) aObj;
Time b = (Time) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 24;
}
@Override
public void write(DataBuffer buff, Object obj) {
Time t = (Time) obj;
writeValue(buff, ValueTime.get(t));
}
@Override
public void writeValue(DataBuffer buff, Value v) {<FILL_FUNCTION_BODY>}
@Override
public Value readValue(ByteBuffer buff) {
long nanos = DataUtils.readVarLong(buff) * 1000000 + DataUtils.readVarLong(buff);
return ValueTime.fromNanos(nanos);
}
};
}
|
ValueTime t = (ValueTime) v;
long nanos = t.getNanos();
long millis = nanos / 1000000;
nanos -= millis * 1000000;
buff.put((byte) TIME).putVarLong(millis).putVarLong(nanos);
| 1,773
| 89
| 1,862
|
<methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/net/NetNode.java
|
NetNode
|
hashCode
|
class NetNode implements Comparable<NetNode> {
private static NetNode localTcpNode = new NetNode(Constants.DEFAULT_HOST,
Constants.DEFAULT_TCP_PORT);
private static NetNode localP2pNode = new NetNode(Constants.DEFAULT_HOST,
Constants.DEFAULT_P2P_PORT);
public static void setLocalTcpNode(String host, int port) {
localTcpNode = new NetNode(host, port);
}
public static NetNode getLocalTcpNode() {
return localTcpNode;
}
public static String getLocalTcpHostAndPort() {
return localTcpNode.getHostAndPort();
}
public static void setLocalP2pNode(String host, int port) {
localP2pNode = new NetNode(host, port);
}
public static NetNode getLocalP2pNode() {
return localP2pNode;
}
private final InetAddress inetAddress;
private final InetSocketAddress inetSocketAddress;
private final String host;
private final int port;
private final String hostAndPort; // host + ":" + port;
public NetNode(String host, int port) {
this.host = host;
this.port = port;
inetSocketAddress = new InetSocketAddress(host, port);
inetAddress = inetSocketAddress.getAddress();
hostAndPort = host + ":" + port;
}
public NetNode(InetAddress inetAddress, int port) {
this.inetAddress = inetAddress;
this.host = inetAddress.getHostAddress();
this.port = port;
inetSocketAddress = new InetSocketAddress(host, port);
hostAndPort = host + ":" + port;
}
public static NetNode getByName(String str) throws UnknownHostException {
return createP2P(str);
}
public static NetNode createP2P(String str) {
return new NetNode(str, true);
}
public static NetNode createTCP(String str) {
return new NetNode(str, false);
}
public static NetNode create(String str, boolean p2p) {
return new NetNode(str, p2p);
}
public NetNode(String str, boolean p2p) {
int port = p2p ? Constants.DEFAULT_P2P_PORT : Constants.DEFAULT_TCP_PORT;
// IPv6: RFC 2732 format is '[a:b:c:d:e:f:g:h]' or
// '[a:b:c:d:e:f:g:h]:port'
// RFC 2396 format is 'a.b.c.d' or 'a.b.c.d:port' or 'hostname' or
// 'hostname:port'
int startIndex = str.startsWith("[") ? str.indexOf(']') : 0;
int idx = str.indexOf(':', startIndex);
if (idx >= 0) {
port = Integer.decode(str.substring(idx + 1));
str = str.substring(0, idx);
}
this.host = str;
this.port = port;
this.inetSocketAddress = new InetSocketAddress(this.host, this.port);
inetAddress = inetSocketAddress.getAddress();
hostAndPort = host + ":" + port;
}
public String getHostAddress() {
return inetAddress.getHostAddress(); // 不能用getHostName(),很慢
}
public String getHostAndPort() {
return hostAndPort;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public byte[] getAddress() {
return inetAddress.getAddress();
}
public InetAddress geInetAddress() {
return inetAddress;
}
public InetSocketAddress getInetSocketAddress() {
return inetSocketAddress;
}
@Override
public String toString() {
return "[host=" + host + ", port=" + port + "]";
}
private String tcpHostAndPort;
public void setTcpHostAndPort(String tcpHostAndPort) {
this.tcpHostAndPort = tcpHostAndPort;
}
public String getTcpHostAndPort() {
return tcpHostAndPort;
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NetNode other = (NetNode) obj;
if (inetAddress == null) {
if (other.inetAddress != null)
return false;
} else if (!inetAddress.equals(other.inetAddress))
return false;
if (port != other.port)
return false;
return true;
}
@Override
public int compareTo(NetNode o) {
int v = this.getHostAddress().compareTo(o.getHostAddress());
if (v == 0) {
return this.port - o.port;
}
return v;
}
public void serialize(DataOutput out) throws IOException {
byte[] bytes = getAddress(); // Inet4Address是4个字节,Inet6Address是16个字节
out.writeByte(bytes.length);
out.write(bytes);
out.writeInt(getPort());
}
public static NetNode deserialize(DataInput in) throws IOException {
byte[] bytes = new byte[in.readByte()];
in.readFully(bytes, 0, bytes.length);
int port = in.readInt();
return new NetNode(InetAddress.getByAddress(bytes), port);
}
public static boolean isLocalTcpNode(String hostId) {
return isLocalTcpNode(NetNode.createTCP(hostId));
}
public static boolean isLocalTcpNode(NetNode n) {
return NetNode.getLocalTcpNode().equals(n);
}
public static boolean isLocalP2pNode(NetNode n) {
return NetNode.getLocalP2pNode().equals(n);
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((inetAddress == null) ? 0 : inetAddress.hashCode());
result = prime * result + port;
return result;
| 1,654
| 58
| 1,712
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/ProtocolServerEngineBase.java
|
ProtocolServerEngineBase
|
getProtocolServer
|
class ProtocolServerEngineBase extends PluginBase implements ProtocolServerEngine {
protected ProtocolServer protocolServer;
public ProtocolServerEngineBase(String name) {
super(name);
}
protected abstract ProtocolServer createProtocolServer();
@Override
public ProtocolServer getProtocolServer() {<FILL_FUNCTION_BODY>}
@Override
public void init(Map<String, String> config) {
super.init(config);
getProtocolServer().init(config);
}
@Override
public void close() {
stop();
super.close();
}
@Override
public void start() {
getProtocolServer().start();
super.start();
}
@Override
public void stop() {
getProtocolServer().stop();
super.stop();
}
@Override
public Class<? extends Plugin> getPluginClass() {
return ProtocolServerEngine.class;
}
}
|
if (protocolServer == null)
protocolServer = createProtocolServer();
return protocolServer;
| 249
| 27
| 276
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public synchronized void close() ,public Map<java.lang.String,java.lang.String> getConfig() ,public java.lang.String getName() ,public Class<? extends com.lealone.db.Plugin> getPluginClass() ,public com.lealone.db.Plugin.State getState() ,public synchronized void init(Map<java.lang.String,java.lang.String>) ,public boolean isInited() ,public boolean isStarted() ,public boolean isStopped() ,public void setName(java.lang.String) ,public void start() ,public void stop() <variables>protected Map<java.lang.String,java.lang.String> config,protected java.lang.String name,protected com.lealone.db.Plugin.State state
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/batch/BatchStatementPreparedUpdate.java
|
Decoder
|
decode
|
class Decoder implements PacketDecoder<BatchStatementPreparedUpdate> {
@Override
public BatchStatementPreparedUpdate decode(NetInputStream in, int version) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int commandId = in.readInt();
int size = in.readInt();
ArrayList<Value[]> batchParameters = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
int len = in.readInt();
Value[] values = new Value[len];
for (int j = 0; j < len; j++)
values[j] = in.readValue();
batchParameters.add(values);
}
return new BatchStatementPreparedUpdate(commandId, size, batchParameters);
| 60
| 138
| 198
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/batch/BatchStatementUpdate.java
|
Decoder
|
decode
|
class Decoder implements PacketDecoder<BatchStatementUpdate> {
@Override
public BatchStatementUpdate decode(NetInputStream in, int version) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int size = in.readInt();
ArrayList<String> batchStatements = new ArrayList<>(size);
for (int i = 0; i < size; i++)
batchStatements.add(in.readString());
return new BatchStatementUpdate(size, batchStatements);
| 54
| 73
| 127
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/batch/BatchStatementUpdateAck.java
|
Decoder
|
decode
|
class Decoder implements PacketDecoder<BatchStatementUpdateAck> {
@Override
public BatchStatementUpdateAck decode(NetInputStream in, int version) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int size = in.readInt();
int[] results = new int[size];
for (int i = 0; i < size; i++)
results[i] = in.readInt();
return new BatchStatementUpdateAck(size, results);
| 58
| 67
| 125
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/ps/PreparedStatementGetMetaDataAck.java
|
PreparedStatementGetMetaDataAck
|
encode
|
class PreparedStatementGetMetaDataAck implements AckPacket {
public final Result result;
public final int columnCount;
public final NetInputStream in;
public PreparedStatementGetMetaDataAck(Result result) {
this.result = result;
columnCount = result.getVisibleColumnCount();
in = null;
}
public PreparedStatementGetMetaDataAck(NetInputStream in, int columnCount) {
result = null;
this.columnCount = columnCount;
this.in = in;
}
@Override
public PacketType getType() {
return PacketType.PREPARED_STATEMENT_GET_META_DATA_ACK;
}
@Override
public void encode(NetOutputStream out, int version) throws IOException {<FILL_FUNCTION_BODY>}
public static final Decoder decoder = new Decoder();
private static class Decoder implements PacketDecoder<PreparedStatementGetMetaDataAck> {
@Override
public PreparedStatementGetMetaDataAck decode(NetInputStream in, int version)
throws IOException {
int columnCount = in.readInt();
return new PreparedStatementGetMetaDataAck(in, columnCount);
}
}
/**
* Write a result column to the given output.
*
* @param result the result
* @param i the column index
*/
public static void writeColumn(NetOutputStream out, Result result, int i) throws IOException {
out.writeString(result.getAlias(i));
out.writeString(result.getSchemaName(i));
out.writeString(result.getTableName(i));
out.writeString(result.getColumnName(i));
out.writeInt(result.getColumnType(i));
out.writeLong(result.getColumnPrecision(i));
out.writeInt(result.getColumnScale(i));
out.writeInt(result.getDisplaySize(i));
out.writeBoolean(result.isAutoIncrement(i));
out.writeInt(result.getNullable(i));
}
}
|
out.writeInt(columnCount);
for (int i = 0; i < columnCount; i++) {
writeColumn(out, result, i);
}
| 531
| 45
| 576
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/ps/PreparedStatementPrepare.java
|
Decoder
|
decode
|
class Decoder implements PacketDecoder<PreparedStatementPrepare> {
@Override
public PreparedStatementPrepare decode(NetInputStream in, int version) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int commandId = in.readInt();
String sql = in.readString();
return new PreparedStatementPrepare(commandId, sql);
| 60
| 40
| 100
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/ps/PreparedStatementPrepareReadParams.java
|
Decoder
|
decode
|
class Decoder implements PacketDecoder<PreparedStatementPrepareReadParams> {
@Override
public PreparedStatementPrepareReadParams decode(NetInputStream in, int version)
throws IOException {<FILL_FUNCTION_BODY>}
}
|
int commandId = in.readInt();
String sql = in.readString();
return new PreparedStatementPrepareReadParams(commandId, sql);
| 66
| 42
| 108
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/ps/PreparedStatementPrepareReadParamsAck.java
|
ClientCommandParameter
|
checkSet
|
class ClientCommandParameter implements CommandParameter {
private final int index;
private Value value;
private int dataType = Value.UNKNOWN;
private long precision;
private int scale;
private int nullable = ResultSetMetaData.columnNullableUnknown;
public ClientCommandParameter(int index) {
this.index = index;
}
@Override
public int getIndex() {
return index;
}
@Override
public void setValue(Value newValue, boolean closeOld) {
if (closeOld && value != null) {
value.close();
}
value = newValue;
}
@Override
public void setValue(Value value) {
this.value = value;
}
@Override
public Value getValue() {
return value;
}
@Override
public void checkSet() {<FILL_FUNCTION_BODY>}
@Override
public boolean isValueSet() {
return value != null;
}
@Override
public int getType() {
return value == null ? dataType : value.getType();
}
@Override
public long getPrecision() {
return value == null ? precision : value.getPrecision();
}
@Override
public int getScale() {
return value == null ? scale : value.getScale();
}
@Override
public int getNullable() {
return nullable;
}
/**
* Read the parameter meta data from the out object.
*
* @param in the NetInputStream
*/
public void readMetaData(NetInputStream in) throws IOException {
dataType = in.readInt();
precision = in.readLong();
scale = in.readInt();
nullable = in.readInt();
}
}
|
if (value == null) {
throw DbException.get(ErrorCode.PARAMETER_NOT_SET_1, "#" + (index + 1));
}
| 466
| 45
| 511
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/ps/PreparedStatementQuery.java
|
PreparedStatementQuery
|
encode
|
class PreparedStatementQuery extends QueryPacket {
public final int commandId;
public final Value[] parameters;
public PreparedStatementQuery(int resultId, int maxRows, int fetchSize, boolean scrollable,
int commandId, Value[] parameters) {
super(resultId, maxRows, fetchSize, scrollable);
this.commandId = commandId;
this.parameters = parameters;
}
public PreparedStatementQuery(NetInputStream in, int version) throws IOException {
super(in, version);
commandId = in.readInt();
int size = in.readInt();
parameters = new Value[size];
for (int i = 0; i < size; i++)
parameters[i] = in.readValue();
}
@Override
public PacketType getType() {
return PacketType.PREPARED_STATEMENT_QUERY;
}
@Override
public PacketType getAckType() {
return PacketType.STATEMENT_QUERY_ACK; // 跟StatementQuery一样
}
@Override
public void encode(NetOutputStream out, int version) throws IOException {<FILL_FUNCTION_BODY>}
public static final Decoder decoder = new Decoder();
private static class Decoder implements PacketDecoder<PreparedStatementQuery> {
@Override
public PreparedStatementQuery decode(NetInputStream in, int version) throws IOException {
return new PreparedStatementQuery(in, version);
}
}
}
|
super.encode(out, version);
out.writeInt(commandId);
int size = parameters.length;
out.writeInt(size);
for (int i = 0; i < size; i++) {
out.writeValue(parameters[i]);
}
| 378
| 72
| 450
|
<methods>public void <init>(int, int, int, boolean) ,public void <init>(com.lealone.net.NetInputStream, int) throws java.io.IOException,public void encode(com.lealone.net.NetOutputStream, int) throws java.io.IOException<variables>public final non-sealed int fetchSize,public final non-sealed int maxRows,public final non-sealed int resultId,public final non-sealed boolean scrollable
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/ps/PreparedStatementUpdate.java
|
PreparedStatementUpdate
|
encode
|
class PreparedStatementUpdate implements Packet {
public final int commandId;
public final Value[] parameters;
public PreparedStatementUpdate(int commandId, Value[] parameters) {
this.commandId = commandId;
this.parameters = parameters;
}
public PreparedStatementUpdate(NetInputStream in, int version) throws IOException {
commandId = in.readInt();
int size = in.readInt();
parameters = new Value[size];
for (int i = 0; i < size; i++)
parameters[i] = in.readValue();
}
@Override
public PacketType getType() {
return PacketType.PREPARED_STATEMENT_UPDATE;
}
@Override
public PacketType getAckType() {
return PacketType.STATEMENT_UPDATE_ACK;
}
@Override
public void encode(NetOutputStream out, int version) throws IOException {<FILL_FUNCTION_BODY>}
public static final Decoder decoder = new Decoder();
private static class Decoder implements PacketDecoder<PreparedStatementUpdate> {
@Override
public PreparedStatementUpdate decode(NetInputStream in, int version) throws IOException {
return new PreparedStatementUpdate(in, version);
}
}
}
|
int size = parameters.length;
out.writeInt(commandId);
out.writeInt(size);
for (int i = 0; i < size; i++) {
out.writeValue(parameters[i]);
}
| 327
| 62
| 389
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/result/ResultFetchRowsAck.java
|
Decoder
|
writeRow
|
class Decoder implements PacketDecoder<ResultFetchRowsAck> {
@Override
public ResultFetchRowsAck decode(NetInputStream in, int version) throws IOException {
return new ResultFetchRowsAck(in);
}
}
public static void writeRow(NetOutputStream out, Result result, int count) throws IOException {<FILL_FUNCTION_BODY>
|
try {
int visibleColumnCount = result.getVisibleColumnCount();
for (int i = 0; i < count; i++) {
if (result.next()) {
out.writeBoolean(true);
Value[] v = result.currentRow();
for (int j = 0; j < visibleColumnCount; j++) {
out.writeValue(v[j]);
}
} else {
out.writeBoolean(false);
break;
}
}
} catch (Throwable e) {
// 如果取结果集的下一行记录时发生了异常,
// 结果集包必须加一个结束标记,结果集包后面跟一个异常包。
out.writeBoolean(false);
throw DbException.convert(e);
}
| 96
| 197
| 293
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/session/SessionInit.java
|
SessionInit
|
encode
|
class SessionInit implements Packet {
public final ConnectionInfo ci;
public final int clientVersion;
public SessionInit(ConnectionInfo ci) {
this.ci = ci;
this.clientVersion = 0;
}
public SessionInit(ConnectionInfo ci, int clientVersion) {
this.ci = ci;
this.clientVersion = clientVersion;
}
@Override
public PacketType getType() {
return PacketType.SESSION_INIT;
}
@Override
public PacketType getAckType() {
return PacketType.SESSION_INIT_ACK;
}
@Override
public void encode(NetOutputStream out, int version) throws IOException {<FILL_FUNCTION_BODY>}
public static final PacketDecoder<SessionInit> decoder = new Decoder();
private static class Decoder implements PacketDecoder<SessionInit> {
@Override
public SessionInit decode(NetInputStream in, int version) throws IOException {
int minClientVersion = in.readInt();
if (minClientVersion < Constants.TCP_PROTOCOL_VERSION_MIN) {
throw DbException.get(ErrorCode.DRIVER_VERSION_ERROR_2, "" + minClientVersion,
"" + Constants.TCP_PROTOCOL_VERSION_MIN);
} else if (minClientVersion > Constants.TCP_PROTOCOL_VERSION_MAX) {
throw DbException.get(ErrorCode.DRIVER_VERSION_ERROR_2, "" + minClientVersion,
"" + Constants.TCP_PROTOCOL_VERSION_MAX);
}
int clientVersion;
int maxClientVersion = in.readInt();
if (maxClientVersion >= Constants.TCP_PROTOCOL_VERSION_MAX) {
clientVersion = Constants.TCP_PROTOCOL_VERSION_CURRENT;
} else {
clientVersion = minClientVersion;
}
ConnectionInfo ci = createConnectionInfo(in);
return new SessionInit(ci, clientVersion);
}
private ConnectionInfo createConnectionInfo(NetInputStream in) throws IOException {
String dbName = in.readString();
String originalURL = in.readString();
String userName = in.readString();
ConnectionInfo ci = new ConnectionInfo(originalURL, dbName);
ci.setUserName(userName);
ci.setUserPasswordHash(in.readBytes());
ci.setFilePasswordHash(in.readBytes());
ci.setFileEncryptionKey(in.readBytes());
int len = in.readInt();
for (int i = 0; i < len; i++) {
String key = in.readString();
String value = in.readString();
ci.addProperty(key, value, true); // 一些不严谨的client driver可能会发送重复的属性名
}
ci.initTraceProperty();
return ci;
}
}
}
|
out.setSSL(ci.isSSL());
out.writeInt(Constants.TCP_PROTOCOL_VERSION_MIN); // minClientVersion
out.writeInt(Constants.TCP_PROTOCOL_VERSION_MAX); // maxClientVersion
out.writeString(ci.getDatabaseName());
out.writeString(ci.getURL()); // 不带参数的URL
out.writeString(ci.getUserName());
out.writeBytes(ci.getUserPasswordHash());
out.writeBytes(ci.getFilePasswordHash());
out.writeBytes(ci.getFileEncryptionKey());
String[] keys = ci.getKeys(true);
out.writeInt(keys.length);
for (String key : keys) {
out.writeString(key).writeString(ci.getProperty(key));
}
| 736
| 207
| 943
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/session/SessionInitAck.java
|
SessionInitAck
|
encode
|
class SessionInitAck implements AckPacket {
public final int clientVersion;
public final boolean autoCommit;
public final String targetNodes;
public final RunMode runMode;
public final boolean invalid;
public final int consistencyLevel;
public SessionInitAck(int clientVersion, boolean autoCommit, String targetNodes, RunMode runMode,
boolean invalid, int consistencyLevel) {
this.clientVersion = clientVersion;
this.autoCommit = autoCommit;
this.targetNodes = targetNodes;
this.runMode = runMode;
this.invalid = invalid;
this.consistencyLevel = consistencyLevel;
}
@Override
public PacketType getType() {
return PacketType.SESSION_INIT_ACK;
}
@Override
public void encode(NetOutputStream out, int version) throws IOException {<FILL_FUNCTION_BODY>}
public static final Decoder decoder = new Decoder();
private static class Decoder implements PacketDecoder<SessionInitAck> {
@Override
public SessionInitAck decode(NetInputStream in, int version) throws IOException {
int clientVersion = in.readInt();
boolean autoCommit = in.readBoolean();
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_6) {
String targetNodes = in.readString();
RunMode runMode = RunMode.valueOf(in.readString());
boolean invalid = in.readBoolean();
int consistencyLevel = in.readInt();
return new SessionInitAck(clientVersion, autoCommit, targetNodes, runMode, invalid,
consistencyLevel);
} else {
return new SessionInitAck(clientVersion, autoCommit, null, RunMode.CLIENT_SERVER, false,
0);
}
}
}
}
|
out.writeInt(clientVersion);
out.writeBoolean(autoCommit);
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_6) {
out.writeString(targetNodes);
out.writeString(runMode.toString());
out.writeBoolean(invalid);
out.writeInt(consistencyLevel);
}
| 459
| 91
| 550
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/server/protocol/statement/StatementQueryAck.java
|
StatementQueryAck
|
encode
|
class StatementQueryAck implements AckPacket {
public final Result result;
public final int rowCount;
public final int columnCount;
public final int fetchSize;
public final NetInputStream in;
public StatementQueryAck(Result result, int rowCount, int fetchSize) {
this.result = result;
this.rowCount = rowCount;
this.fetchSize = fetchSize;
columnCount = result.getVisibleColumnCount();
in = null;
}
public StatementQueryAck(NetInputStream in, int version) throws IOException {
result = null;
rowCount = in.readInt();
columnCount = in.readInt();
fetchSize = in.readInt();
this.in = in;
}
@Override
public PacketType getType() {
return PacketType.STATEMENT_QUERY_ACK;
}
@Override
public void encode(NetOutputStream out, int version) throws IOException {<FILL_FUNCTION_BODY>}
// ----------------------------------------------------------------
// 因为查询结果集是lazy解码的,所以子类的字段需要提前编码和解码
// ----------------------------------------------------------------
public void encodeExt(NetOutputStream out, int version) throws IOException {
}
public static final Decoder decoder = new Decoder();
private static class Decoder implements PacketDecoder<StatementQueryAck> {
@Override
public StatementQueryAck decode(NetInputStream in, int version) throws IOException {
return new StatementQueryAck(in, version);
}
}
}
|
out.writeInt(rowCount);
out.writeInt(columnCount);
out.writeInt(fetchSize);
encodeExt(out, version);
for (int i = 0; i < columnCount; i++) {
PreparedStatementGetMetaDataAck.writeColumn(out, result, i);
}
ResultFetchRowsAck.writeRow(out, result, fetchSize);
| 396
| 102
| 498
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/StorageBase.java
|
StorageBase
|
closeImmediately
|
class StorageBase implements Storage {
protected static final String TEMP_NAME_PREFIX = Constants.NAME_SEPARATOR + "temp"
+ Constants.NAME_SEPARATOR;
protected final Map<StorageEventListener, StorageEventListener> listeners = new ConcurrentHashMap<>();
protected final Map<String, StorageMap<?, ?>> maps = new ConcurrentHashMap<>();
protected final Map<String, Object> config;
protected boolean closed;
protected SchedulerFactory schedulerFactory;
public StorageBase(Map<String, Object> config) {
this.config = config;
}
@Override
public void closeMap(String name) {
StorageMap<?, ?> map = maps.remove(name);
if (map != null)
map.close();
}
@Override
public boolean hasMap(String name) {
return maps.containsKey(name);
}
@Override
public StorageMap<?, ?> getMap(String name) {
return maps.get(name);
}
@Override
public Set<String> getMapNames() {
return new HashSet<>(maps.keySet());
}
@Override
public String nextTemporaryMapName() {
int i = 0;
String name = null;
while (true) {
name = TEMP_NAME_PREFIX + i++;
if (!maps.containsKey(name))
return name;
}
}
@Override
public String getStoragePath() {
return (String) config.get(StorageSetting.STORAGE_PATH.name());
}
@Override
public boolean isInMemory() {
return false;
}
@Override
public long getDiskSpaceUsed() {
long total = 0;
for (StorageMap<?, ?> map : maps.values())
total += map.getDiskSpaceUsed();
return total;
}
@Override
public long getMemorySpaceUsed() {
long total = 0;
for (StorageMap<?, ?> map : maps.values())
total += map.getMemorySpaceUsed();
return total;
}
@Override
public void save() {
for (StorageMap<?, ?> map : maps.values())
map.save();
}
@Override
public void drop() {
close();
if (!isInMemory())
FileUtils.deleteRecursive(getStoragePath(), false);
}
@Override
public void backupTo(String fileName, Long lastDate) {
if (isInMemory())
return;
save();
backupFiles(fileName, lastDate);
}
@Override
public void backupTo(String baseDir, ZipOutputStream out, Long lastDate) {
if (isInMemory())
return;
save();
try {
backupFiles(baseDir, out, lastDate);
} catch (IOException e) {
throw DbException.convertIOException(e, "");
}
}
@Override
public void close() {
for (StorageEventListener listener : listeners.values())
listener.beforeClose(this);
listeners.clear();
save();
closeImmediately();
}
@Override
public void closeImmediately() {<FILL_FUNCTION_BODY>}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void registerEventListener(StorageEventListener listener) {
listeners.put(listener, listener);
}
@Override
public void unregisterEventListener(StorageEventListener listener) {
listeners.remove(listener);
}
@Override
public SchedulerFactory getSchedulerFactory() {
return schedulerFactory;
}
@Override
public void setSchedulerFactory(SchedulerFactory schedulerFactory) {
this.schedulerFactory = schedulerFactory;
}
protected InputStream getInputStream(String mapName, FilePath file) throws IOException {
return file.newInputStream();
}
private void backupFiles(String toFile, Long lastDate) {
try (ZipOutputStream out = createZipOutputStream(toFile)) {
backupFiles(null, out, lastDate);
} catch (IOException e) {
throw DbException.convertIOException(e, toFile);
}
}
private void backupFiles(String baseDir, ZipOutputStream out, Long lastDate) throws IOException {
if (baseDir != null)
baseDir = new File(baseDir).getCanonicalPath().replace('\\', '/');
String path = new File(getStoragePath()).getCanonicalPath(); // 可能是一个文件或目录
FilePath p = FilePath.get(path);
if (p.isDirectory()) {
String pathShortName = path.replace('\\', '/');
if (baseDir != null && pathShortName.startsWith(baseDir))
pathShortName = pathShortName.substring(baseDir.length() + 1);
else
pathShortName = pathShortName.substring(pathShortName.lastIndexOf('/') + 1);
FilePath dir = FilePath.get(path);
for (FilePath map : dir.newDirectoryStream()) {
String mapName = map.getName();
String entryNameBase = pathShortName + "/" + mapName;
for (FilePath file : map.newDirectoryStream()) {
if (lastDate == null || file.lastModified() > lastDate.longValue())
backupFile(out, getInputStream(mapName, file),
entryNameBase + "/" + file.getName());
}
}
} else {
backupFile(out, p.newInputStream(), p.getName());
}
}
private static void backupFile(ZipOutputStream out, InputStream in, String entryName)
throws IOException {
if (in == null)
return;
out.putNextEntry(new ZipEntry(entryName));
IOUtils.copyAndCloseInput(in, out);
out.closeEntry();
}
public static ZipOutputStream createZipOutputStream(String fileName) throws IOException {
if (!fileName.toLowerCase().endsWith(".zip"))
fileName += ".zip";
return new ZipOutputStream(FileUtils.newOutputStream(fileName, false));
}
}
|
closed = true;
for (StorageMap<?, ?> map : maps.values())
map.close();
maps.clear();
| 1,583
| 39
| 1,622
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/StorageMapBase.java
|
StorageMapBase
|
setMaxKey
|
class StorageMapBase<K, V> implements StorageMap<K, V> {
protected final String name;
protected final StorageDataType keyType;
protected final StorageDataType valueType;
protected final Storage storage;
protected final AtomicLong maxKey = new AtomicLong(0);
protected StorageMapBase(String name, StorageDataType keyType, StorageDataType valueType,
Storage storage) {
DataUtils.checkNotNull(name, "name");
if (keyType == null) {
keyType = new ObjectDataType();
}
if (valueType == null) {
valueType = new ObjectDataType();
}
this.name = name;
this.keyType = keyType;
this.valueType = valueType;
this.storage = storage;
}
@Override
public String getName() {
return name;
}
@Override
public StorageDataType getKeyType() {
return keyType;
}
@Override
public StorageDataType getValueType() {
return valueType;
}
@Override
public Storage getStorage() {
return storage;
}
// 如果新key比maxKey大就更新maxKey
// 允许多线程并发更新
@Override
public void setMaxKey(K key) {<FILL_FUNCTION_BODY>}
private void setMaxKey(long key) {
while (true) {
long old = maxKey.get();
if (key > old) {
if (maxKey.compareAndSet(old, key))
break;
} else {
break;
}
}
}
@Override
public long getAndAddKey(long delta) {
return maxKey.getAndAdd(delta);
}
public long getMaxKey() {
return maxKey.get();
}
public long incrementAndGetMaxKey() {
return maxKey.incrementAndGet();
}
private final ConcurrentHashMap<Object, Object> oldValueCache = new ConcurrentHashMap<>(1);
@Override
public ConcurrentHashMap<Object, Object> getOldValueCache() {
return oldValueCache;
}
}
|
if (key instanceof ValueLong) {
setMaxKey(((ValueLong) key).getLong());
} else if (key instanceof Number) {
setMaxKey(((Number) key).longValue());
}
| 564
| 56
| 620
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/FileStorageInputStream.java
|
FileStorageInputStream
|
read
|
class FileStorageInputStream extends InputStream {
private FileStorage fileStorage;
private final boolean alwaysClose;
private final CompressTool compress;
private final DataBuffer page;
private final boolean raw;
private int remainingInBuffer;
private boolean endOfFile;
public FileStorageInputStream(FileStorage fileStorage, DataHandler handler, boolean compression,
boolean alwaysClose) {
this(fileStorage, handler, compression, alwaysClose, false);
}
public FileStorageInputStream(FileStorage fileStorage, DataHandler handler, boolean compression,
boolean alwaysClose, boolean raw) {
this.fileStorage = fileStorage;
this.alwaysClose = alwaysClose;
this.raw = raw;
if (compression) {
compress = CompressTool.getInstance();
} else {
compress = null;
}
int capacity = raw ? Constants.IO_BUFFER_SIZE : Constants.FILE_BLOCK_SIZE;
page = DataBuffer.create(handler, capacity, false); // 不能用direct byte buffer
try {
fillBuffer();
} catch (IOException e) {
throw DbException.convertIOException(e, fileStorage.getFileName());
}
}
@Override
public int available() {
return remainingInBuffer <= 0 ? 0 : remainingInBuffer;
}
@Override
public int read() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int read(byte[] buff) throws IOException {
return read(buff, 0, buff.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (len == 0) {
return 0;
}
int read = 0;
while (len > 0) {
int r = readBlock(b, off, len);
if (r < 0) {
break;
}
read += r;
off += r;
len -= r;
}
return read == 0 ? -1 : read;
}
private int readBlock(byte[] buff, int off, int len) throws IOException {
fillBuffer();
if (endOfFile) {
return -1;
}
int l = Math.min(remainingInBuffer, len);
page.read(buff, off, l);
remainingInBuffer -= l;
return l;
}
private void fillBuffer() throws IOException {
if (remainingInBuffer > 0 || endOfFile) {
return;
}
page.reset();
if (raw) {
remainingInBuffer = (int) Math.min(fileStorage.length() - fileStorage.getFilePointer(),
Constants.IO_BUFFER_SIZE);
if (remainingInBuffer <= 0) {
endOfFile = true;
} else {
fileStorage.readFully(page.getBytes(), 0, remainingInBuffer);
}
return;
}
fileStorage.openFile();
if (fileStorage.length() == fileStorage.getFilePointer()) {
close();
return;
}
fileStorage.readFully(page.getBytes(), 0, Constants.FILE_BLOCK_SIZE);
page.reset();
remainingInBuffer = page.getInt();
if (remainingInBuffer < 0) {
close();
return;
}
page.checkCapacity(remainingInBuffer);
// get the length to rea
if (compress != null) {
page.checkCapacity(DataBuffer.LENGTH_INT);
page.getInt();
}
page.setPos(page.length() + remainingInBuffer);
page.fillAligned();
int len = page.length() - Constants.FILE_BLOCK_SIZE;
page.reset();
page.getInt();
fileStorage.readFully(page.getBytes(), Constants.FILE_BLOCK_SIZE, len);
page.reset();
page.getInt();
if (compress != null) {
int uncompressed = page.getInt();
byte[] buff = DataUtils.newBytes(remainingInBuffer);
page.read(buff, 0, remainingInBuffer);
page.reset();
page.checkCapacity(uncompressed);
CompressTool.expand(buff, page.getBytes(), 0);
remainingInBuffer = uncompressed;
}
if (alwaysClose) {
fileStorage.closeFile();
}
}
@Override
public void close() {
if (raw)
return;
if (fileStorage != null) {
try {
fileStorage.close();
endOfFile = true;
} finally {
fileStorage = null;
}
}
}
@Override
protected void finalize() {
close();
}
}
|
fillBuffer();
if (endOfFile) {
return -1;
}
int i = page.readByte() & 0xff;
remainingInBuffer--;
return i;
| 1,220
| 54
| 1,274
|
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/FileStorageOutputStream.java
|
FileStorageOutputStream
|
write
|
class FileStorageOutputStream extends OutputStream {
private FileStorage fileStorage;
private final CompressTool compress;
private final String compressionAlgorithm;
private final DataBuffer page;
private final byte[] buffer = { 0 };
public FileStorageOutputStream(FileStorage fs, DataHandler handler, String compressionAlgorithm) {
this.fileStorage = fs;
if (compressionAlgorithm != null) {
this.compress = CompressTool.getInstance();
this.compressionAlgorithm = compressionAlgorithm;
} else {
this.compress = null;
this.compressionAlgorithm = null;
}
page = DataBuffer.create(handler, Constants.FILE_BLOCK_SIZE, false); // 不能用direct byte buffer
}
@Override
public void write(int b) {
buffer[0] = (byte) b;
write(buffer);
}
@Override
public void write(byte[] buff) {
write(buff, 0, buff.length);
}
@Override
public void write(byte[] buff, int off, int len) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
if (fileStorage != null) {
try {
fileStorage.close();
} finally {
fileStorage = null;
}
}
}
}
|
if (len > 0) {
page.reset();
if (compress != null) {
if (off != 0 || len != buff.length) {
byte[] b2 = new byte[len];
System.arraycopy(buff, off, b2, 0, len);
buff = b2;
off = 0;
}
int uncompressed = len;
buff = compress.compress(buff, compressionAlgorithm);
len = buff.length;
page.putInt(len);
page.putInt(uncompressed);
page.put(buff, off, len);
} else {
page.putInt(len);
page.put(buff, off, len);
}
page.fillAligned();
fileStorage.write(page.getBytes(), 0, page.length());
}
| 346
| 216
| 562
|
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/impl/FileBase.java
|
FileBase
|
write
|
class FileBase extends FileChannel {
@Override
public abstract long size() throws IOException;
@Override
public abstract long position() throws IOException;
@Override
public abstract FileChannel position(long newPosition) throws IOException;
@Override
public abstract int read(ByteBuffer dst) throws IOException;
@Override
public abstract int write(ByteBuffer src) throws IOException;
@Override
public synchronized int read(ByteBuffer dst, long position) throws IOException {
long oldPos = position();
position(position);
int len = read(dst);
position(oldPos);
return len;
}
@Override
public synchronized int write(ByteBuffer src, long position) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public abstract FileChannel truncate(long size) throws IOException;
@Override
public void force(boolean metaData) throws IOException {
// ignore
}
@Override
protected void implCloseChannel() throws IOException {
// ignore
}
@Override
public FileLock lock(long position, long size, boolean shared) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long transferTo(long position, long count, WritableByteChannel target) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public FileLock tryLock(long position, long size, boolean shared) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
throw new UnsupportedOperationException();
}
}
|
long oldPos = position();
position(position);
int len = write(src);
position(oldPos);
return len;
| 533
| 38
| 571
|
<methods>public abstract void force(boolean) throws java.io.IOException,public final java.nio.channels.FileLock lock() throws java.io.IOException,public abstract java.nio.channels.FileLock lock(long, long, boolean) throws java.io.IOException,public abstract java.nio.MappedByteBuffer map(java.nio.channels.FileChannel.MapMode, long, long) throws java.io.IOException,public static transient java.nio.channels.FileChannel open(java.nio.file.Path, java.nio.file.OpenOption[]) throws java.io.IOException,public static transient java.nio.channels.FileChannel open(java.nio.file.Path, Set<? extends java.nio.file.OpenOption>, FileAttribute<?>[]) throws java.io.IOException,public abstract long position() throws java.io.IOException,public abstract java.nio.channels.FileChannel position(long) throws java.io.IOException,public abstract int read(java.nio.ByteBuffer) throws java.io.IOException,public final long read(java.nio.ByteBuffer[]) throws java.io.IOException,public abstract int read(java.nio.ByteBuffer, long) throws java.io.IOException,public abstract long read(java.nio.ByteBuffer[], int, int) throws java.io.IOException,public abstract long size() throws java.io.IOException,public abstract long transferFrom(java.nio.channels.ReadableByteChannel, long, long) throws java.io.IOException,public abstract long transferTo(long, long, java.nio.channels.WritableByteChannel) throws java.io.IOException,public abstract java.nio.channels.FileChannel truncate(long) throws java.io.IOException,public final java.nio.channels.FileLock tryLock() throws java.io.IOException,public abstract java.nio.channels.FileLock tryLock(long, long, boolean) throws java.io.IOException,public abstract int write(java.nio.ByteBuffer) throws java.io.IOException,public final long write(java.nio.ByteBuffer[]) throws java.io.IOException,public abstract int write(java.nio.ByteBuffer, long) throws java.io.IOException,public abstract long write(java.nio.ByteBuffer[], int, int) throws java.io.IOException<variables>private static final FileAttribute<?>[] NO_ATTRIBUTES
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/impl/FileChannelInputStream.java
|
FileChannelInputStream
|
read
|
class FileChannelInputStream extends InputStream {
private final FileChannel channel;
private final boolean closeChannel;
private ByteBuffer buffer;
private long pos;
/**
* Create a new file object input stream from the file channel.
*
* @param channel the file channel
* @param closeChannel whether closing the stream should close the channel
*/
public FileChannelInputStream(FileChannel channel, boolean closeChannel) {
this.channel = channel;
this.closeChannel = closeChannel;
}
@Override
public int read() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
ByteBuffer buff = ByteBuffer.wrap(b, off, len);
int read = channel.read(buff, pos);
if (read == -1) {
return -1;
}
pos += read;
return read;
}
@Override
public void close() throws IOException {
if (closeChannel) {
channel.close();
}
}
}
|
if (buffer == null) {
buffer = ByteBuffer.allocate(1);
}
buffer.rewind();
int len = channel.read(buffer, pos++);
if (len < 0) {
return -1;
}
return buffer.get(0) & 0xff;
| 310
| 81
| 391
|
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/impl/FilePathWrapper.java
|
FilePathWrapper
|
wrap
|
class FilePathWrapper extends FilePath {
private FilePath base;
@Override
public FilePathWrapper getPath(String path) {
return create(path, unwrap(path));
}
/**
* Create a wrapped path instance for the given base path.
*
* @param base the base path
* @return the wrapped path
*/
public FilePathWrapper wrap(FilePath base) {<FILL_FUNCTION_BODY>}
@Override
public FilePath unwrap() {
return unwrap(name);
}
private FilePathWrapper create(String path, FilePath base) {
try {
FilePathWrapper p = getClass().getDeclaredConstructor().newInstance();
p.name = path;
p.base = base;
return p;
} catch (Exception e) {
throw new IllegalArgumentException("Path: " + path, e);
}
}
protected String getPrefix() {
return getScheme() + ":";
}
/**
* Get the base path for the given wrapped path.
*
* @param path the path including the scheme prefix
* @return the base file path
*/
protected FilePath unwrap(String path) {
return FilePath.get(path.substring(getScheme().length() + 1));
}
protected FilePath getBase() {
return base;
}
@Override
public boolean canWrite() {
return base.canWrite();
}
@Override
public void createDirectory() {
base.createDirectory();
}
@Override
public boolean createFile() {
return base.createFile();
}
@Override
public void delete() {
base.delete();
}
@Override
public boolean exists() {
return base.exists();
}
@Override
public FilePath getParent() {
return wrap(base.getParent());
}
@Override
public boolean isAbsolute() {
return base.isAbsolute();
}
@Override
public boolean isDirectory() {
return base.isDirectory();
}
@Override
public long lastModified() {
return base.lastModified();
}
@Override
public FilePath toRealPath() {
return wrap(base.toRealPath());
}
@Override
public List<FilePath> newDirectoryStream() {
List<FilePath> list = base.newDirectoryStream();
for (int i = 0, len = list.size(); i < len; i++) {
list.set(i, wrap(list.get(i)));
}
return list;
}
@Override
public void moveTo(FilePath newName, boolean atomicReplace) {
base.moveTo(((FilePathWrapper) newName).base, atomicReplace);
}
@Override
public InputStream newInputStream() throws IOException {
return base.newInputStream();
}
@Override
public OutputStream newOutputStream(boolean append) throws IOException {
return base.newOutputStream(append);
}
@Override
public FileChannel open(String mode) throws IOException {
return base.open(mode);
}
@Override
public boolean setReadOnly() {
return base.setReadOnly();
}
@Override
public long size() {
return base.size();
}
@Override
public FilePath createTempFile(String suffix, boolean deleteOnExit, boolean inTempDir)
throws IOException {
return wrap(base.createTempFile(suffix, deleteOnExit, inTempDir));
}
}
|
return base == null ? null : create(getPrefix() + base.name, base);
| 923
| 24
| 947
|
<methods>public non-sealed void <init>() ,public abstract boolean canWrite() ,public abstract void createDirectory() ,public abstract boolean createFile() ,public com.lealone.storage.fs.FilePath createTempFile(java.lang.String, boolean, boolean) throws java.io.IOException,public abstract void delete() ,public abstract boolean exists() ,public static com.lealone.storage.fs.FilePath get(java.lang.String) ,public java.lang.String getName() ,public abstract com.lealone.storage.fs.FilePath getParent() ,public abstract com.lealone.storage.fs.FilePath getPath(java.lang.String) ,public abstract java.lang.String getScheme() ,public abstract boolean isAbsolute() ,public abstract boolean isDirectory() ,public abstract long lastModified() ,public abstract void moveTo(com.lealone.storage.fs.FilePath, boolean) ,public abstract List<com.lealone.storage.fs.FilePath> newDirectoryStream() ,public abstract java.io.InputStream newInputStream() throws java.io.IOException,public abstract java.io.OutputStream newOutputStream(boolean) throws java.io.IOException,public abstract java.nio.channels.FileChannel open(java.lang.String) throws java.io.IOException,public static void register(com.lealone.storage.fs.FilePath) ,public abstract boolean setReadOnly() ,public abstract long size() ,public abstract com.lealone.storage.fs.FilePath toRealPath() ,public java.lang.String toString() ,public static void unregister(com.lealone.storage.fs.FilePath) ,public com.lealone.storage.fs.FilePath unwrap() <variables>private static com.lealone.storage.fs.FilePath defaultProvider,public java.lang.String name,private static Map<java.lang.String,com.lealone.storage.fs.FilePath> providers,private static java.lang.String tempRandom,private static long tempSequence
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/impl/disk/FileDisk.java
|
FileDisk
|
read
|
class FileDisk extends FileBase {
private final RandomAccessFile file;
private final String name;
private final boolean readOnly;
FileDisk(String fileName, String mode) throws FileNotFoundException {
this.file = new RandomAccessFile(fileName, mode);
this.name = fileName;
this.readOnly = mode.equals("r");
}
@Override
public void force(boolean metaData) throws IOException {
String m = SysProperties.SYNC_METHOD;
if ("".equals(m)) {
// do nothing
} else if ("sync".equals(m)) {
file.getFD().sync();
} else if ("force".equals(m)) {
file.getChannel().force(true);
} else if ("forceFalse".equals(m)) {
file.getChannel().force(false);
} else {
file.getFD().sync();
}
}
@Override
public FileChannel truncate(long newLength) throws IOException {
// compatibility with JDK FileChannel#truncate
if (readOnly) {
throw new NonWritableChannelException();
}
if (newLength < file.length()) {
file.setLength(newLength);
}
return this;
}
@Override
public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException {
return file.getChannel().tryLock(position, size, shared);
}
@Override
public void implCloseChannel() throws IOException {
file.close();
}
@Override
public long position() throws IOException {
return file.getFilePointer();
}
@Override
public long size() throws IOException {
return file.length();
}
@Override
public int read(ByteBuffer dst) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public FileChannel position(long pos) throws IOException {
file.seek(pos);
return this;
}
@Override
public int write(ByteBuffer src) throws IOException {
int len = src.remaining();
file.write(src.array(), src.arrayOffset() + src.position(), len);
src.position(src.position() + len);
return len;
}
@Override
public String toString() {
return name;
}
}
|
int len = file.read(dst.array(), dst.arrayOffset() + dst.position(), dst.remaining());
if (len > 0) {
dst.position(dst.position() + len);
}
return len;
| 599
| 67
| 666
|
<methods>public non-sealed void <init>() ,public void force(boolean) throws java.io.IOException,public java.nio.channels.FileLock lock(long, long, boolean) throws java.io.IOException,public java.nio.MappedByteBuffer map(java.nio.channels.FileChannel.MapMode, long, long) throws java.io.IOException,public abstract long position() throws java.io.IOException,public abstract java.nio.channels.FileChannel position(long) throws java.io.IOException,public abstract int read(java.nio.ByteBuffer) throws java.io.IOException,public synchronized int read(java.nio.ByteBuffer, long) throws java.io.IOException,public long read(java.nio.ByteBuffer[], int, int) throws java.io.IOException,public abstract long size() throws java.io.IOException,public long transferFrom(java.nio.channels.ReadableByteChannel, long, long) throws java.io.IOException,public long transferTo(long, long, java.nio.channels.WritableByteChannel) throws java.io.IOException,public abstract java.nio.channels.FileChannel truncate(long) throws java.io.IOException,public java.nio.channels.FileLock tryLock(long, long, boolean) throws java.io.IOException,public abstract int write(java.nio.ByteBuffer) throws java.io.IOException,public synchronized int write(java.nio.ByteBuffer, long) throws java.io.IOException,public long write(java.nio.ByteBuffer[], int, int) throws java.io.IOException<variables>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/impl/encrypt/FileEncrypt.java
|
XTS
|
xorTweak
|
class XTS {
/**
* Galois field feedback.
*/
private static final int GF_128_FEEDBACK = 0x87;
/**
* The AES encryption block size.
*/
private static final int CIPHER_BLOCK_SIZE = 16;
private final BlockCipher cipher;
XTS(BlockCipher cipher) {
this.cipher = cipher;
}
/**
* Encrypt the data.
*
* @param id the (sector) id
* @param len the number of bytes
* @param data the data
* @param offset the offset within the data
*/
void encrypt(long id, int len, byte[] data, int offset) {
byte[] tweak = initTweak(id);
int i = 0;
for (; i + CIPHER_BLOCK_SIZE <= len; i += CIPHER_BLOCK_SIZE) {
if (i > 0) {
updateTweak(tweak);
}
xorTweak(data, i + offset, tweak);
cipher.encrypt(data, i + offset, CIPHER_BLOCK_SIZE);
xorTweak(data, i + offset, tweak);
}
if (i < len) {
updateTweak(tweak);
swap(data, i + offset, i - CIPHER_BLOCK_SIZE + offset, len - i);
xorTweak(data, i - CIPHER_BLOCK_SIZE + offset, tweak);
cipher.encrypt(data, i - CIPHER_BLOCK_SIZE + offset, CIPHER_BLOCK_SIZE);
xorTweak(data, i - CIPHER_BLOCK_SIZE + offset, tweak);
}
}
/**
* Decrypt the data.
*
* @param id the (sector) id
* @param len the number of bytes
* @param data the data
* @param offset the offset within the data
*/
void decrypt(long id, int len, byte[] data, int offset) {
byte[] tweak = initTweak(id), tweakEnd = tweak;
int i = 0;
for (; i + CIPHER_BLOCK_SIZE <= len; i += CIPHER_BLOCK_SIZE) {
if (i > 0) {
updateTweak(tweak);
if (i + CIPHER_BLOCK_SIZE + CIPHER_BLOCK_SIZE > len && i + CIPHER_BLOCK_SIZE < len) {
tweakEnd = Arrays.copyOf(tweak, CIPHER_BLOCK_SIZE);
updateTweak(tweak);
}
}
xorTweak(data, i + offset, tweak);
cipher.decrypt(data, i + offset, CIPHER_BLOCK_SIZE);
xorTweak(data, i + offset, tweak);
}
if (i < len) {
swap(data, i, i - CIPHER_BLOCK_SIZE + offset, len - i + offset);
xorTweak(data, i - CIPHER_BLOCK_SIZE + offset, tweakEnd);
cipher.decrypt(data, i - CIPHER_BLOCK_SIZE + offset, CIPHER_BLOCK_SIZE);
xorTweak(data, i - CIPHER_BLOCK_SIZE + offset, tweakEnd);
}
}
private byte[] initTweak(long id) {
byte[] tweak = new byte[CIPHER_BLOCK_SIZE];
for (int j = 0; j < CIPHER_BLOCK_SIZE; j++, id >>>= 8) {
tweak[j] = (byte) (id & 0xff);
}
cipher.encrypt(tweak, 0, CIPHER_BLOCK_SIZE);
return tweak;
}
private static void xorTweak(byte[] data, int pos, byte[] tweak) {<FILL_FUNCTION_BODY>}
private static void updateTweak(byte[] tweak) {
byte ci = 0, co = 0;
for (int i = 0; i < CIPHER_BLOCK_SIZE; i++) {
co = (byte) ((tweak[i] >> 7) & 1);
tweak[i] = (byte) (((tweak[i] << 1) + ci) & 255);
ci = co;
}
if (co != 0) {
tweak[0] ^= GF_128_FEEDBACK;
}
}
private static void swap(byte[] data, int source, int target, int len) {
for (int i = 0; i < len; i++) {
byte temp = data[source + i];
data[source + i] = data[target + i];
data[target + i] = temp;
}
}
}
|
for (int i = 0; i < CIPHER_BLOCK_SIZE; i++) {
data[pos + i] ^= tweak[i];
}
| 1,255
| 45
| 1,300
|
<methods>public non-sealed void <init>() ,public void force(boolean) throws java.io.IOException,public java.nio.channels.FileLock lock(long, long, boolean) throws java.io.IOException,public java.nio.MappedByteBuffer map(java.nio.channels.FileChannel.MapMode, long, long) throws java.io.IOException,public abstract long position() throws java.io.IOException,public abstract java.nio.channels.FileChannel position(long) throws java.io.IOException,public abstract int read(java.nio.ByteBuffer) throws java.io.IOException,public synchronized int read(java.nio.ByteBuffer, long) throws java.io.IOException,public long read(java.nio.ByteBuffer[], int, int) throws java.io.IOException,public abstract long size() throws java.io.IOException,public long transferFrom(java.nio.channels.ReadableByteChannel, long, long) throws java.io.IOException,public long transferTo(long, long, java.nio.channels.WritableByteChannel) throws java.io.IOException,public abstract java.nio.channels.FileChannel truncate(long) throws java.io.IOException,public java.nio.channels.FileLock tryLock(long, long, boolean) throws java.io.IOException,public abstract int write(java.nio.ByteBuffer) throws java.io.IOException,public synchronized int write(java.nio.ByteBuffer, long) throws java.io.IOException,public long write(java.nio.ByteBuffer[], int, int) throws java.io.IOException<variables>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/impl/encrypt/FilePathEncrypt.java
|
FilePathEncrypt
|
parse
|
class FilePathEncrypt extends FilePathWrapper {
private static final String SCHEME = "encrypt";
/**
* Register this file system.
*/
public static void register() {
FilePath.register(new FilePathEncrypt());
}
@Override
public String getScheme() {
return SCHEME;
}
@Override
public FileChannel open(String mode) throws IOException {
String[] parsed = parse(name);
FileChannel file = FileUtils.open(parsed[1], mode);
byte[] passwordBytes = parsed[0].getBytes(Constants.UTF8);
return new FileEncrypt(name, passwordBytes, file);
}
@Override
protected String getPrefix() {
String[] parsed = parse(name);
return getScheme() + ":" + parsed[0] + ":";
}
@Override
public FilePath unwrap(String fileName) {
return FilePath.get(parse(fileName)[1]);
}
@Override
public long size() {
long size = getBase().size() - FileEncrypt.HEADER_LENGTH;
size = Math.max(0, size);
if ((size & FileEncrypt.BLOCK_SIZE_MASK) != 0) {
size -= FileEncrypt.BLOCK_SIZE;
}
return size;
}
@Override
public OutputStream newOutputStream(boolean append) throws IOException {
return new FileChannelOutputStream(open("rw"), append);
}
@Override
public InputStream newInputStream() throws IOException {
return new FileChannelInputStream(open("r"), true);
}
/**
* Split the file name into algorithm, password, and base file name.
*
* @param fileName the file name
* @return an array with algorithm, password, and base file name
*/
private String[] parse(String fileName) {<FILL_FUNCTION_BODY>}
/**
* Convert a char array to a byte array, in UTF-16 format. The char array is
* not cleared after use (this must be done by the caller).
*
* @param passwordChars the password characters
* @return the byte array
*/
public static byte[] getPasswordBytes(char[] passwordChars) {
// using UTF-16
int len = passwordChars.length;
byte[] password = new byte[len * 2];
for (int i = 0; i < len; i++) {
char c = passwordChars[i];
password[i + i] = (byte) (c >>> 8);
password[i + i + 1] = (byte) c;
}
return password;
}
}
|
if (!fileName.startsWith(getScheme())) {
throw new IllegalArgumentException(fileName + " doesn't start with " + getScheme());
}
fileName = fileName.substring(getScheme().length() + 1);
int idx = fileName.indexOf(':');
String password;
if (idx < 0) {
throw new IllegalArgumentException(fileName //
+ " doesn't contain encryption algorithm and password");
}
password = fileName.substring(0, idx);
fileName = fileName.substring(idx + 1);
return new String[] { password, fileName };
| 690
| 157
| 847
|
<methods>public non-sealed void <init>() ,public boolean canWrite() ,public void createDirectory() ,public boolean createFile() ,public com.lealone.storage.fs.FilePath createTempFile(java.lang.String, boolean, boolean) throws java.io.IOException,public void delete() ,public boolean exists() ,public com.lealone.storage.fs.FilePath getParent() ,public com.lealone.storage.fs.impl.FilePathWrapper getPath(java.lang.String) ,public boolean isAbsolute() ,public boolean isDirectory() ,public long lastModified() ,public void moveTo(com.lealone.storage.fs.FilePath, boolean) ,public List<com.lealone.storage.fs.FilePath> newDirectoryStream() ,public java.io.InputStream newInputStream() throws java.io.IOException,public java.io.OutputStream newOutputStream(boolean) throws java.io.IOException,public java.nio.channels.FileChannel open(java.lang.String) throws java.io.IOException,public boolean setReadOnly() ,public long size() ,public com.lealone.storage.fs.FilePath toRealPath() ,public com.lealone.storage.fs.FilePath unwrap() ,public com.lealone.storage.fs.impl.FilePathWrapper wrap(com.lealone.storage.fs.FilePath) <variables>private com.lealone.storage.fs.FilePath base
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/fs/impl/nio/FileNio.java
|
FileNio
|
truncate
|
class FileNio extends FileBase {
private final String fileName;
private final RandomAccessFile file;
private final FileChannel channel;
FileNio(String fileName, String mode) throws IOException {
this.fileName = fileName;
file = new RandomAccessFile(fileName, mode);
channel = file.getChannel();
}
@Override
public void implCloseChannel() throws IOException {
file.close(); // 内部会调用channel.close()
}
@Override
public long position() throws IOException {
return channel.position();
}
@Override
public long size() throws IOException {
return channel.size();
}
@Override
public int read(ByteBuffer dst) throws IOException {
return channel.read(dst);
}
@Override
public FileChannel position(long pos) throws IOException {
channel.position(pos);
return this;
}
@Override
public int read(ByteBuffer dst, long position) throws IOException {
return channel.read(dst, position);
}
@Override
public int write(ByteBuffer src, long position) throws IOException {
return channel.write(src, position);
}
@Override
public FileChannel truncate(long newLength) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void force(boolean metaData) throws IOException {
channel.force(metaData);
}
@Override
public int write(ByteBuffer src) throws IOException {
try {
return channel.write(src);
} catch (NonWritableChannelException e) {
throw new IOException("read only");
}
}
@Override
public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException {
return channel.tryLock(position, size, shared);
}
@Override
public String toString() {
return "nio:" + fileName;
}
}
|
long size = channel.size();
if (newLength < size) {
long pos = channel.position();
channel.truncate(newLength);
long newPos = channel.position();
if (pos < newLength) {
// position should stay
// in theory, this should not be needed
if (newPos != pos) {
channel.position(pos);
}
} else if (newPos > newLength) {
// looks like a bug in this FileChannel implementation, as
// the documentation says the position needs to be changed
channel.position(newLength);
}
}
return this;
| 504
| 160
| 664
|
<methods>public non-sealed void <init>() ,public void force(boolean) throws java.io.IOException,public java.nio.channels.FileLock lock(long, long, boolean) throws java.io.IOException,public java.nio.MappedByteBuffer map(java.nio.channels.FileChannel.MapMode, long, long) throws java.io.IOException,public abstract long position() throws java.io.IOException,public abstract java.nio.channels.FileChannel position(long) throws java.io.IOException,public abstract int read(java.nio.ByteBuffer) throws java.io.IOException,public synchronized int read(java.nio.ByteBuffer, long) throws java.io.IOException,public long read(java.nio.ByteBuffer[], int, int) throws java.io.IOException,public abstract long size() throws java.io.IOException,public long transferFrom(java.nio.channels.ReadableByteChannel, long, long) throws java.io.IOException,public long transferTo(long, long, java.nio.channels.WritableByteChannel) throws java.io.IOException,public abstract java.nio.channels.FileChannel truncate(long) throws java.io.IOException,public java.nio.channels.FileLock tryLock(long, long, boolean) throws java.io.IOException,public abstract int write(java.nio.ByteBuffer) throws java.io.IOException,public synchronized int write(java.nio.ByteBuffer, long) throws java.io.IOException,public long write(java.nio.ByteBuffer[], int, int) throws java.io.IOException<variables>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/lob/LobLocalStorage.java
|
LobLocalStorage
|
createBlob
|
class LobLocalStorage implements LobStorage {
private final DataHandler handler;
private final LobReader lobReader;
public LobLocalStorage(DataHandler handler, LobReader lobReader) {
this.handler = handler;
this.lobReader = lobReader;
}
@Override
public ValueLob createBlob(InputStream in, long maxLength) {<FILL_FUNCTION_BODY>}
@Override
public ValueLob createClob(Reader reader, long maxLength) {
// need to use a temp file, because the input stream could come from
// the same database, which would create a weird situation (trying
// to read a block while writing something)
return ValueLob.createTempClob(reader, maxLength, handler);
}
@Override
public InputStream getInputStream(ValueLob lob, byte[] hmac, long byteCount) throws IOException {
if (byteCount < 0) {
byteCount = Long.MAX_VALUE;
}
return new BufferedInputStream(new LobInputStream(lobReader, lob, hmac, byteCount));
}
@Override
public void setTable(ValueLob lob, int tableIdSessionVariable) {
throw new UnsupportedOperationException();
}
@Override
public void removeAllForTable(int tableId) {
throw new UnsupportedOperationException();
}
@Override
public void removeLob(ValueLob lob) {
// not stored in the database
}
/**
* An input stream that reads from a remote LOB.
*/
private static class LobInputStream extends InputStream {
private final LobReader lobReader;
private final long lobId;
private final byte[] hmac;
private long pos;
/**
* The remaining bytes in the lob.
*/
private long remainingBytes;
LobInputStream(LobReader lobReader, ValueLob lob, byte[] hmac, long byteCount) {
this.lobReader = lobReader;
this.lobId = lob.getLobId();
this.hmac = hmac;
remainingBytes = byteCount;
}
@Override
public int read() throws IOException {
byte[] buff = new byte[1];
int len = read(buff, 0, 1);
return len < 0 ? len : (buff[0] & 255);
}
@Override
public int read(byte[] buff) throws IOException {
return read(buff, 0, buff.length);
}
@Override
public int read(byte[] buff, int off, int length) throws IOException {
if (length == 0) {
return 0;
}
length = (int) Math.min(length, remainingBytes);
if (length == 0) {
return -1;
}
try {
length = lobReader.readLob(lobId, hmac, pos, buff, off, length);
} catch (DbException e) {
throw DbException.convertToIOException(e);
}
remainingBytes -= length;
if (length == 0) {
return -1;
}
pos += length;
return length;
}
@Override
public long skip(long n) {
remainingBytes -= n;
pos += n;
return n;
}
}
public static interface LobReader {
/**
* Read from a lob.
*
* @param lobId the lob
* @param hmac the message authentication code
* @param offset the offset within the lob
* @param buff the target buffer
* @param off the offset within the target buffer
* @param length the number of bytes to read
* @return the number of bytes read
*/
int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length);
}
}
|
// need to use a temp file, because the input stream could come from
// the same database, which would create a weird situation (trying
// to read a block while writing something)
return ValueLob.createTempBlob(in, maxLength, handler);
| 985
| 66
| 1,051
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/type/BigIntegerType.java
|
BigIntegerType
|
read
|
class BigIntegerType extends StorageDataTypeBase {
@Override
public int getType() {
return TYPE_BIG_INTEGER;
}
@Override
public int compare(Object aObj, Object bObj) {
BigInteger a = (BigInteger) aObj;
BigInteger b = (BigInteger) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 100;
}
@Override
public void write(DataBuffer buff, Object obj) {
BigInteger x = (BigInteger) obj;
if (BigInteger.ZERO.equals(x)) {
buff.put((byte) TAG_BIG_INTEGER_0);
} else if (BigInteger.ONE.equals(x)) {
buff.put((byte) TAG_BIG_INTEGER_1);
} else {
int bits = x.bitLength();
if (bits <= 63) {
buff.put((byte) TAG_BIG_INTEGER_SMALL).putVarLong(x.longValue());
} else {
byte[] bytes = x.toByteArray();
buff.put((byte) TYPE_BIG_INTEGER).putVarInt(bytes.length).put(bytes);
}
}
}
@Override
public Object read(ByteBuffer buff, int tag) {<FILL_FUNCTION_BODY>}
}
|
switch (tag) {
case TAG_BIG_INTEGER_0:
return BigInteger.ZERO;
case TAG_BIG_INTEGER_1:
return BigInteger.ONE;
case TAG_BIG_INTEGER_SMALL:
return BigInteger.valueOf(DataUtils.readVarLong(buff));
}
int len = DataUtils.readVarInt(buff);
byte[] bytes = DataUtils.newBytes(len);
buff.get(bytes);
return new BigInteger(bytes);
| 371
| 140
| 511
|
<methods>public non-sealed void <init>() ,public abstract int getType() ,public java.lang.Object read(java.nio.ByteBuffer) ,public java.lang.Object read(java.nio.ByteBuffer, int) ,public com.lealone.db.value.Value readValue(java.nio.ByteBuffer) ,public com.lealone.db.value.Value readValue(java.nio.ByteBuffer, int) ,public void writeValue(com.lealone.db.DataBuffer, com.lealone.db.value.Value) <variables>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/type/CharacterType.java
|
CharacterType
|
compare
|
class CharacterType extends StorageDataTypeBase {
@Override
public int getType() {
return TYPE_CHAR;
}
@Override
public int compare(Object aObj, Object bObj) {<FILL_FUNCTION_BODY>}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
buff.put((byte) TYPE_CHAR);
buff.putChar(((Character) obj).charValue());
}
@Override
public Object read(ByteBuffer buff, int tag) {
return Character.valueOf(buff.getChar());
}
}
|
Character a = (Character) aObj;
Character b = (Character) bObj;
return a.compareTo(b);
| 177
| 35
| 212
|
<methods>public non-sealed void <init>() ,public abstract int getType() ,public java.lang.Object read(java.nio.ByteBuffer) ,public java.lang.Object read(java.nio.ByteBuffer, int) ,public com.lealone.db.value.Value readValue(java.nio.ByteBuffer) ,public com.lealone.db.value.Value readValue(java.nio.ByteBuffer, int) ,public void writeValue(com.lealone.db.DataBuffer, com.lealone.db.value.Value) <variables>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/type/ObjectDataType.java
|
ObjectDataType
|
getTypeId
|
class ObjectDataType implements StorageDataType {
private StorageDataTypeBase last = ValueString.type;
@Override
public int compare(Object a, Object b) {
switchType(a);
return last.compare(a, b);
}
@Override
public int getMemory(Object obj) {
switchType(obj);
return last.getMemory(obj);
}
@Override
public void write(DataBuffer buff, Object obj) {
switchType(obj);
last.write(buff, obj);
}
@Override
public Object read(ByteBuffer buff) {
int tag = buff.get();
int typeId = StorageDataType.getTypeId(tag);
return switchType(typeId).read(buff, tag);
}
private StorageDataTypeBase switchType(int typeId) {
StorageDataTypeBase l = last;
if (typeId != l.getType()) {
last = l = newType(typeId);
}
return l;
}
/**
* Switch the last remembered type to match the type of the given object.
*
* @param obj the object
* @return the auto-detected type used
*/
StorageDataTypeBase switchType(Object obj) {
int typeId = getTypeId(obj);
return switchType(typeId);
}
/**
* Compare the contents of two byte arrays. If the content or length of the
* first array is smaller than the second array, -1 is returned. If the
* content or length of the second array is smaller than the first array, 1
* is returned. If the contents and lengths are the same, 0 is returned.
* <p>
* This method interprets bytes as unsigned.
*
* @param data1 the first byte array (must not be null)
* @param data2 the second byte array (must not be null)
* @return the result of the comparison (-1, 1 or 0)
*/
static int compareNotNull(byte[] data1, byte[] data2) {
if (data1 == data2) {
return 0;
}
int len = Math.min(data1.length, data2.length);
for (int i = 0; i < len; i++) {
int b = data1[i] & 255;
int b2 = data2[i] & 255;
if (b != b2) {
return b > b2 ? 1 : -1;
}
}
return Integer.signum(data1.length - data2.length);
}
private static boolean isBigInteger(Object obj) {
return obj instanceof BigInteger && obj.getClass() == BigInteger.class;
}
private static boolean isBigDecimal(Object obj) {
return obj instanceof BigDecimal && obj.getClass() == BigDecimal.class;
}
private static boolean isDate(Object obj) {
return obj instanceof Date && obj.getClass() == Date.class;
}
private static boolean isTime(Object obj) {
return obj instanceof Time && obj.getClass() == Time.class;
}
private static boolean isTimestamp(Object obj) {
return obj instanceof Timestamp && obj.getClass() == Timestamp.class;
}
private static boolean isArray(Object obj) {
return obj != null && obj.getClass().isArray();
}
private static StorageDataTypeBase newType(int typeId) {
switch (typeId) {
case TYPE_NULL:
return ValueNull.type;
case TYPE_BOOLEAN:
return ValueBoolean.type;
case TYPE_BYTE:
return ValueByte.type;
case TYPE_SHORT:
return ValueShort.type;
case TYPE_CHAR:
return new CharacterType();
case TYPE_INT:
return ValueInt.type;
case TYPE_LONG:
return ValueLong.type;
case TYPE_FLOAT:
return ValueFloat.type;
case TYPE_DOUBLE:
return ValueDouble.type;
case TYPE_BIG_INTEGER:
return new BigIntegerType();
case TYPE_BIG_DECIMAL:
return ValueDecimal.type;
case TYPE_STRING:
return ValueString.type;
case TYPE_UUID:
return ValueUuid.type;
case TYPE_DATE:
return ValueDate.type;
case TYPE_TIME:
return ValueTime.type;
case TYPE_TIMESTAMP:
return ValueTimestamp.type;
case TYPE_ARRAY:
return new ObjectArrayType();
case TYPE_SERIALIZED_OBJECT:
return new SerializedObjectType();
}
throw DataUtils.newIllegalStateException(DataUtils.ERROR_INTERNAL, "Unsupported type {0}",
typeId);
}
private static int getTypeId(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (obj instanceof Integer) {
return TYPE_INT;
} else if (obj instanceof String) {
return TYPE_STRING;
} else if (obj instanceof Long) {
return TYPE_LONG;
} else if (obj instanceof Double) {
return TYPE_DOUBLE;
} else if (obj instanceof Float) {
return TYPE_FLOAT;
} else if (obj instanceof Boolean) {
return TYPE_BOOLEAN;
} else if (obj instanceof UUID) {
return TYPE_UUID;
} else if (obj instanceof Byte) {
return TYPE_BYTE;
} else if (obj instanceof Short) {
return TYPE_SHORT;
} else if (obj instanceof Character) {
return TYPE_CHAR;
} else if (obj == null) {
return TYPE_NULL;
} else if (isDate(obj)) {
return TYPE_DATE;
} else if (isTime(obj)) {
return TYPE_TIME;
} else if (isTimestamp(obj)) {
return TYPE_TIMESTAMP;
} else if (isBigInteger(obj)) {
return TYPE_BIG_INTEGER;
} else if (isBigDecimal(obj)) {
return TYPE_BIG_DECIMAL;
} else if (isArray(obj)) {
return TYPE_ARRAY;
}
return TYPE_SERIALIZED_OBJECT;
| 1,263
| 357
| 1,620
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/storage/type/SerializedObjectType.java
|
SerializedObjectType
|
getMemory
|
class SerializedObjectType extends StorageDataTypeBase {
private int averageSize = 10000;
private final ObjectDataType base = new ObjectDataType();
@Override
public int getType() {
return TYPE_SERIALIZED_OBJECT;
}
@Override
@SuppressWarnings("unchecked")
public int compare(Object aObj, Object bObj) {
if (aObj == bObj) {
return 0;
}
StorageDataType ta = getType(aObj);
StorageDataType tb = getType(bObj);
if (ta.getClass() != this.getClass() || tb.getClass() != this.getClass()) {
if (ta == tb) {
return ta.compare(aObj, bObj);
}
}
// TODO ensure comparable type (both may be comparable but not
// with each other)
if (aObj instanceof Comparable) {
if (aObj.getClass().isAssignableFrom(bObj.getClass())) {
return ((Comparable<Object>) aObj).compareTo(bObj);
}
}
if (bObj instanceof Comparable) {
if (bObj.getClass().isAssignableFrom(aObj.getClass())) {
return -((Comparable<Object>) bObj).compareTo(aObj);
}
}
byte[] a = serialize(aObj);
byte[] b = serialize(bObj);
return ObjectDataType.compareNotNull(a, b);
}
private StorageDataType getType(Object obj) {
return base.switchType(obj);
}
@Override
public int getMemory(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public void write(DataBuffer buff, Object obj) {
StorageDataType t = getType(obj);
if (t != this) {
t.write(buff, obj);
return;
}
byte[] data = serialize(obj);
// we say they are larger, because these objects
// use quite a lot of disk space
int size = data.length * 2;
// adjust the average size
// using an exponential moving average
averageSize = (size + 15 * averageSize) / 16;
buff.put((byte) TYPE_SERIALIZED_OBJECT).putVarInt(data.length).put(data);
}
@Override
public Object read(ByteBuffer buff, int tag) {
int len = DataUtils.readVarInt(buff);
byte[] data = DataUtils.newBytes(len);
buff.get(data);
return deserialize(data);
}
/**
* Serialize the object to a byte array.
*
* @param obj the object to serialize
* @return the byte array
*/
private static byte[] serialize(Object obj) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
} catch (Throwable e) {
throw DataUtils.newIllegalArgumentException("Could not serialize {0}", obj, e);
}
}
/**
* De-serialize the byte array to an object.
*
* @param data the byte array
* @return the object
*/
private static Object deserialize(byte[] data) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
} catch (Throwable e) {
throw DataUtils.newIllegalArgumentException("Could not deserialize {0}",
Arrays.toString(data), e);
}
}
}
|
StorageDataType t = getType(obj);
if (t.getClass() == this.getClass()) {
return averageSize;
}
return t.getMemory(obj);
| 965
| 50
| 1,015
|
<methods>public non-sealed void <init>() ,public abstract int getType() ,public java.lang.Object read(java.nio.ByteBuffer) ,public java.lang.Object read(java.nio.ByteBuffer, int) ,public com.lealone.db.value.Value readValue(java.nio.ByteBuffer) ,public com.lealone.db.value.Value readValue(java.nio.ByteBuffer, int) ,public void writeValue(com.lealone.db.DataBuffer, com.lealone.db.value.Value) <variables>
|
lealone_Lealone
|
Lealone/lealone-common/src/main/java/com/lealone/transaction/PendingTransaction.java
|
PendingTransaction
|
setSynced
|
class PendingTransaction extends LinkableBase<PendingTransaction> {
private final Transaction transaction;
private final Object redoLogRecord;
private final long logId;
private CountDownLatch latch;
private boolean synced;
private boolean completed;
public PendingTransaction(Transaction transaction, Object redoLogRecord, long logId) {
this.transaction = transaction;
this.redoLogRecord = redoLogRecord;
this.logId = logId;
}
public Transaction getTransaction() {
return transaction;
}
public Object getRedoLogRecord() {
return redoLogRecord;
}
public long getLogId() {
return logId;
}
public void setLatch(CountDownLatch latch) {
this.latch = latch;
}
public boolean isSynced() {
return synced;
}
public void setSynced(boolean synced) {<FILL_FUNCTION_BODY>}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public Scheduler getScheduler() {
return transaction.getScheduler();
}
}
|
if (transaction != null)
transaction.onSynced();
this.synced = synced;
if (latch != null)
latch.countDown();
| 326
| 48
| 374
|
<methods>public non-sealed void <init>() ,public com.lealone.transaction.PendingTransaction getNext() ,public void setNext(com.lealone.transaction.PendingTransaction) <variables>public com.lealone.transaction.PendingTransaction next
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/Comment.java
|
Comment
|
getCreateSQL
|
class Comment extends DbObjectBase {
private final DbObjectType objectType;
private final String objectName;
private String commentText;
public Comment(Database database, int id, DbObject obj) {
super(database, id, getKey(obj));
this.objectType = obj.getType();
this.objectName = obj.getSQL();
}
@Override
public DbObjectType getType() {
return DbObjectType.COMMENT;
}
@Override
public String getCreateSQL() {<FILL_FUNCTION_BODY>}
@Override
public void checkRename() {
DbException.throwInternalError();
}
/**
* Set the comment text.
*
* @param comment the text
*/
public void setCommentText(String comment) {
this.commentText = comment;
}
public String getCommentText() {
return commentText;
}
/**
* Get the comment key name for the given database object. This key name is
* used internally to associate the comment to the object.
*
* @param obj the object
* @return the key name
*/
public static String getKey(DbObject obj) {
return getTypeName(obj.getType()) + " " + obj.getSQL();
}
private static String getTypeName(DbObjectType type) {
switch (type) {
case FUNCTION_ALIAS:
return "ALIAS";
case TABLE_OR_VIEW:
return "TABLE";
case USER_DATATYPE:
return "DOMAIN";
default:
return type.name();
}
}
}
|
StringBuilder buff = new StringBuilder("COMMENT ON ");
buff.append(getTypeName(objectType)).append(' ').append(objectName).append(" IS ");
if (commentText == null) {
buff.append("NULL");
} else {
buff.append(StringUtils.quoteStringSQL(commentText));
}
return buff.toString();
| 436
| 92
| 528
|
<methods>public void checkRename() ,public List<? extends com.lealone.db.DbObject> getChildren() ,public java.lang.String getComment() ,public com.lealone.db.Database getDatabase() ,public java.lang.String getDropSQL() ,public int getId() ,public long getModificationId() ,public java.lang.String getName() ,public java.lang.String getSQL() ,public void invalidate() ,public boolean isTemporary() ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public void rename(java.lang.String) ,public void setComment(java.lang.String) ,public void setDatabase(com.lealone.db.Database) ,public void setModified() ,public void setTemporary(boolean) ,public java.lang.String toString() <variables>protected java.lang.String comment,protected com.lealone.db.Database database,protected int id,protected long modificationId,protected java.lang.String name,protected boolean temporary
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/DbObjectBase.java
|
DbObjectBase
|
toString
|
class DbObjectBase implements DbObject {
protected Database database;
protected int id;
protected String name;
protected boolean temporary;
protected String comment;
protected long modificationId;
/**
* Initialize some attributes of this object.
*
* @param db the database
* @param id the object id
* @param name the object name
*/
protected DbObjectBase(Database database, int id, String name) {
this(id, name);
setDatabase(database);
}
protected DbObjectBase(int id, String name) {
this.id = id;
this.name = name;
}
public void setDatabase(Database database) {
this.database = database;
this.modificationId = database.getModificationMetaId();
}
@Override
public Database getDatabase() {
return database;
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getSQL() {
return database.quoteIdentifier(name);
}
@Override
public String getDropSQL() {
return null;
}
@Override
public List<? extends DbObject> getChildren() {
return null;
}
@Override
public void removeChildrenAndResources(ServerSession session, DbObjectLock lock) {
}
@Override
public void checkRename() {
// ok
}
@Override
public void rename(String newName) {
checkRename();
name = newName;
setModified();
}
@Override
public boolean isTemporary() {
return temporary;
}
@Override
public void setTemporary(boolean temporary) {
this.temporary = temporary;
}
@Override
public void setComment(String comment) {
this.comment = comment;
}
@Override
public String getComment() {
return comment;
}
/**
* Tell the object that is was modified.
*/
public void setModified() {
this.modificationId = database == null ? -1 : database.getNextModificationMetaId();
}
public long getModificationId() {
return modificationId;
}
/**
* Set the main attributes to null to make sure the object is no longer used.
*/
@Override
public void invalidate() {
setModified();
database = null;
id = -1;
name = null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return name + ":" + id + ":" + super.toString();
| 700
| 20
| 720
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/LealoneDatabase.java
|
LealoneDatabase
|
closeDatabase
|
class LealoneDatabase extends Database
implements com.lealone.transaction.TransactionEngine.GcTask {
// ID固定为0
public static final int ID = 0;
public static final String NAME = Constants.PROJECT_NAME;
// 仅用于支持qinsql项目
private static final CaseInsensitiveMap<String> UNSUPPORTED_SCHEMA_MAP = new CaseInsensitiveMap<>();
private static final CaseInsensitiveMap<Object[]> CLOSED_DATABASES = new CaseInsensitiveMap<>();
private static LealoneDatabase INSTANCE = new LealoneDatabase();
public static LealoneDatabase getInstance() {
return INSTANCE;
}
public static void addUnsupportedSchema(String schemaName) {
UNSUPPORTED_SCHEMA_MAP.put(schemaName, schemaName);
}
public static boolean isUnsupportedSchema(String schemaName) {
return UNSUPPORTED_SCHEMA_MAP.containsKey(schemaName);
}
public static boolean isMe(String dbName) {
return LealoneDatabase.NAME.equalsIgnoreCase(dbName);
}
private LealoneDatabase() {
super(ID, NAME, null);
// init执行过程中会触发getInstance(),此时INSTANCE为null,会导致NPE
INSTANCE = this;
// 把自己也加进去,这样通过lealone这个名字能找到自己
addDatabaseObject(null, this, null);
init();
createRootUserIfNotExists();
getTransactionEngine().addGcTask(this);
}
public synchronized Database createEmbeddedDatabase(String name, ConnectionInfo ci) {
Database db = findDatabase(name);
if (db != null)
return db;
HashMap<String, String> parameters = new HashMap<>();
for (Entry<Object, Object> e : ci.getProperties().entrySet()) {
parameters.put(e.getKey().toString(), e.getValue().toString());
}
int id = ci.getDatabaseId() < 0 ? INSTANCE.allocateObjectId() : ci.getDatabaseId();
db = new Database(id, name, parameters);
db.setRunMode(RunMode.EMBEDDED);
db.init();
String userName = ci.getUserName();
byte[] userPasswordHash = ci.getUserPasswordHash();
db.createAdminUser(userName, userPasswordHash);
// 新建session,避免使用system session
try (ServerSession session = createSession(getSystemUser())) {
DbObjectLock lock = tryExclusiveDatabaseLock(session);
addDatabaseObject(session, db, lock);
session.commit();
}
return db;
}
void closeDatabase(String dbName) {<FILL_FUNCTION_BODY>}
void dropDatabase(String dbName) {
synchronized (CLOSED_DATABASES) {
CLOSED_DATABASES.remove(dbName);
}
}
Map<String, Database> getDatabasesMap() {
return getDbObjects(DbObjectType.DATABASE);
}
public List<Database> getDatabases() {
synchronized (CLOSED_DATABASES) {
return new ArrayList<>(getDatabasesMap().values());
}
}
public Database findDatabase(String dbName) {
return find(DbObjectType.DATABASE, null, dbName);
}
/**
* Get database with the given name.
* This method throws an exception if the database does not exist.
*
* @param name the database name
* @return the database
* @throws DbException if the database does not exist
*/
public Database getDatabase(String dbName) {
Database db = findDatabase(dbName);
if (db == null) {
synchronized (CLOSED_DATABASES) {
Object[] a = CLOSED_DATABASES.remove(dbName);
if (a != null) {
MetaRecord.execute(this, getSystemSession(), getEventListener(), (String) a[0],
(int) a[1]);
db = findDatabase(dbName);
}
}
}
if (db == null) {
throw DbException.get(ErrorCode.DATABASE_NOT_FOUND_1, dbName);
}
return db;
}
public boolean isClosed(String dbName) {
synchronized (CLOSED_DATABASES) {
return CLOSED_DATABASES.containsKey(dbName);
}
}
@Override
public synchronized Database copy() {
INSTANCE = new LealoneDatabase();
getTransactionEngine().removeGcTask(this);
return INSTANCE;
}
// 只有用管理员连接到LealoneDatabase才能执行某些语句,比如CREATE/ALTER/DROP DATABASE
public static void checkAdminRight(ServerSession session, String stmt) {
if (!isSuperAdmin(session))
throw DbException.get(ErrorCode.LEALONE_DATABASE_ADMIN_RIGHT_1, stmt);
}
public static boolean isSuperAdmin(ServerSession session) {
Database db = session.getDatabase();
// 在MySQL兼容模式下只需要当前用户是管理员即可
if (db.getMode().isMySQL())
return session.getUser().isAdmin();
else
return LealoneDatabase.getInstance() == db && session.getUser().isAdmin();
}
@Override
public void gc(TransactionEngine te) {
// getDatabases()会copy一份,因为closeIfNeeded()可能会关闭数据库,避免ConcurrentModificationException
for (Database db : getDatabases()) {
long metaId = db.getModificationMetaId();
if (metaId == db.getLastGcMetaId())
continue;
db.setLastGcMetaId(metaId);
// 数据库没有进行初始化时不进行GC
if (!db.isInitialized())
continue;
if (db.getSessionCount() == 0 && db.closeIfNeeded())
continue;
for (TransactionalDbObjects tObjects : db.getTransactionalDbObjectsArray()) {
if (tObjects != null)
tObjects.gc(te);
}
for (Schema schema : db.getAllSchemas()) {
for (TransactionalDbObjects tObjects : schema.getTransactionalDbObjectsArray()) {
if (tObjects != null)
tObjects.gc(te);
}
}
}
}
}
|
Database db = findDatabase(dbName);
if (db != null) {
synchronized (CLOSED_DATABASES) {
getDatabasesMap().remove(dbName); // 要放到同步块中
CLOSED_DATABASES.put(dbName, new Object[] { db.getCreateSQL(), db.getId() });
}
}
| 1,666
| 97
| 1,763
|
<methods>public void <init>(int, java.lang.String, Map<java.lang.String,java.lang.String>) ,public void addDataHandler(int, com.lealone.db.DataHandler) ,public void addDatabaseObject(com.lealone.db.session.ServerSession, com.lealone.db.DbObject, com.lealone.db.lock.DbObjectLock) ,public synchronized boolean addWaitingSession(com.lealone.db.session.ServerSession) ,public int allocateObjectId() ,public static void appendMap(com.lealone.common.util.StatementBuilder, Map<java.lang.String,java.lang.String>) ,public boolean areEqual(com.lealone.db.value.Value, com.lealone.db.value.Value) ,public void backupTo(java.lang.String, java.lang.Long) ,public void checkPowerOff() ,public void checkWritingAllowed() ,public void checkpoint() ,public void clearObjectId(int) ,public synchronized boolean closeIfNeeded() ,public int compare(com.lealone.db.value.Value, com.lealone.db.value.Value) ,public int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.Value) ,public synchronized com.lealone.db.Database copy() ,public synchronized com.lealone.db.Database copy(boolean) ,public com.lealone.sql.SQLParser createParser(com.lealone.db.session.Session) ,public void createRootUserIfNotExists() ,public com.lealone.db.session.ServerSession createSession(com.lealone.db.auth.User) ,public synchronized com.lealone.db.session.ServerSession createSession(com.lealone.db.auth.User, com.lealone.db.ConnectionInfo) ,public com.lealone.db.session.ServerSession createSession(com.lealone.db.auth.User, com.lealone.db.scheduler.Scheduler) ,public synchronized com.lealone.db.session.ServerSession createSession(com.lealone.db.auth.User, com.lealone.db.ConnectionInfo, com.lealone.db.scheduler.Scheduler) ,public synchronized void drop() ,public boolean equalsIdentifiers(java.lang.String, java.lang.String) ,public void exceptionThrown(java.sql.SQLException, java.lang.String) ,public com.lealone.db.Comment findComment(com.lealone.db.session.ServerSession, com.lealone.db.DbObject) ,public com.lealone.db.result.Row findMeta(com.lealone.db.session.ServerSession, int) ,public com.lealone.db.PluginObject findPluginObject(com.lealone.db.session.ServerSession, java.lang.String) ,public com.lealone.db.auth.Role findRole(com.lealone.db.session.ServerSession, java.lang.String) ,public com.lealone.db.schema.Schema findSchema(com.lealone.db.session.ServerSession, java.lang.String) ,public com.lealone.db.auth.User findUser(com.lealone.db.session.ServerSession, java.lang.String) ,public ArrayList<com.lealone.db.Comment> getAllComments() ,public ArrayList<com.lealone.db.PluginObject> getAllPluginObjects() ,public ArrayList<com.lealone.db.auth.Right> getAllRights() ,public ArrayList<com.lealone.db.auth.Role> getAllRoles() ,public ArrayList<com.lealone.db.schema.SchemaObject> getAllSchemaObjects() ,public ArrayList<com.lealone.db.schema.SchemaObject> getAllSchemaObjects(com.lealone.db.DbObjectType) ,public ArrayList<com.lealone.db.schema.Schema> getAllSchemas() ,public ArrayList<com.lealone.db.table.Table> getAllTablesAndViews(boolean) ,public ArrayList<com.lealone.db.auth.User> getAllUsers() ,public int getAllowLiterals() ,public int getCacheSize() ,public List<? extends com.lealone.db.DbObject> getChildren() ,public com.lealone.db.value.CompareMode getCompareMode() ,public com.lealone.db.util.SourceCompiler getCompiler() ,public java.lang.String getCreateSQL() ,public java.lang.String getCreateSQL(boolean) ,public com.lealone.db.DataHandler getDataHandler(int) ,public java.lang.String getDatabasePath() ,public java.lang.String getDefaultStorageEngineName() ,public int getDefaultTableType() ,public com.lealone.db.table.Table getDependentTable(com.lealone.db.schema.SchemaObject, com.lealone.db.table.Table) ,public long getDiskSpaceUsed() ,public com.lealone.db.api.DatabaseEventListener getEventListener() ,public com.lealone.db.session.ServerSession getExclusiveSession() ,public byte[] getFileEncryptionKey() ,public com.lealone.db.table.Table getFirstUserTable() ,public java.lang.String[] getHostIds() ,public boolean getIgnoreCase() ,public java.sql.Connection getInternalConnection() ,public java.sql.Connection getInternalConnection(com.lealone.db.scheduler.Scheduler) ,public long getLastGcMetaId() ,public java.lang.String getLobCompressionAlgorithm(int) ,public com.lealone.storage.lob.LobStorage getLobStorage() ,public int getMaxLengthInplaceLob() ,public int getMaxMemoryRows() ,public int getMaxMemoryUndo() ,public int getMaxOperationMemory() ,public com.lealone.db.index.Cursor getMetaCursor(com.lealone.db.session.ServerSession) ,public com.lealone.storage.Storage getMetaStorage() ,public com.lealone.db.Mode getMode() ,public long getModificationDataId() ,public long getModificationMetaId() ,public long getNextModificationDataId() ,public long getNextModificationMetaId() ,public boolean getOptimizeReuseResults() ,public int getPageSize() ,public Map<java.lang.String,java.lang.String> getParameters() ,public com.lealone.db.auth.Role getPublicRole() ,public boolean getQueryStatistics() ,public com.lealone.db.stat.QueryStatisticsData getQueryStatisticsData() ,public boolean getReferentialIntegrity() ,public com.lealone.db.auth.Role getRole(com.lealone.db.session.ServerSession, java.lang.String) ,public com.lealone.db.RunMode getRunMode() ,public java.lang.String getSQL() ,public com.lealone.sql.SQLEngine getSQLEngine() ,public com.lealone.db.scheduler.SchedulerLock getSchedulerLock() ,public com.lealone.db.schema.Schema getSchema(com.lealone.db.session.ServerSession, java.lang.String) ,public synchronized int getSessionCount() ,public com.lealone.db.session.ServerSession[] getSessions(boolean) ,public com.lealone.db.DbSettings getSettings() ,public java.lang.String getShortName() ,public com.lealone.storage.Storage getStorage(java.lang.String) ,public synchronized com.lealone.storage.Storage getStorage(com.lealone.storage.StorageEngine) ,public com.lealone.storage.StorageBuilder getStorageBuilder(com.lealone.storage.StorageEngine, java.lang.String) ,public java.lang.String getStoragePath() ,public List<com.lealone.storage.Storage> getStorages() ,public com.lealone.db.session.ServerSession getSystemSession() ,public com.lealone.db.auth.User getSystemUser() ,public com.lealone.db.table.TableAlterHistory getTableAlterHistory() ,public java.lang.String getTargetNodes() ,public com.lealone.common.util.TempFileDeleter getTempFileDeleter() ,public com.lealone.common.trace.Trace getTrace(com.lealone.common.trace.TraceModuleType) ,public com.lealone.common.trace.TraceSystem getTraceSystem() ,public com.lealone.transaction.TransactionEngine getTransactionEngine() ,public com.lealone.db.TransactionalDbObjects[] getTransactionalDbObjectsArray() ,public com.lealone.db.DbObjectType getType() ,public com.lealone.db.auth.User getUser(com.lealone.db.session.ServerSession, java.lang.String) ,public synchronized void init() ,public boolean isClosing() ,public boolean isInitialized() ,public boolean isMultiVersion() ,public boolean isObjectIdEnabled(int) ,public boolean isOpened() ,public boolean isPersistent() ,public boolean isPowerOff() ,public boolean isReadOnly() ,public boolean isStarting() ,public boolean isSystemSchema(com.lealone.db.schema.Schema) ,public boolean isTargetNode(com.lealone.net.NetNode) ,public boolean isTemporary() ,public void markClosed() ,public HashMap<java.lang.String,V> newStringMap() ,public com.lealone.storage.fs.FileStorage openFile(java.lang.String, java.lang.String, boolean) ,public java.lang.String quoteIdentifier(java.lang.String) ,public void removeDataHandler(int) ,public void removeDatabaseObject(com.lealone.db.session.ServerSession, com.lealone.db.DbObject, com.lealone.db.lock.DbObjectLock) ,public synchronized void removeSession(com.lealone.db.session.ServerSession) ,public void renameDatabaseObject(com.lealone.db.session.ServerSession, com.lealone.db.DbObject, java.lang.String, com.lealone.db.lock.DbObjectLock) ,public synchronized void setCloseDelay(int) ,public void setCompareMode(com.lealone.db.value.CompareMode) ,public boolean setDbSetting(com.lealone.db.session.ServerSession, com.lealone.db.DbSetting, java.lang.String) ,public void setEventListenerClass(java.lang.String) ,public synchronized void setExclusiveSession(com.lealone.db.session.ServerSession, boolean) ,public void setHostIds(java.lang.String[]) ,public void setLastConnectionInfo(com.lealone.db.ConnectionInfo) ,public void setLastGcMetaId(long) ,public void setLobStorage(com.lealone.storage.lob.LobStorage) ,public void setMode(com.lealone.db.Mode) ,public void setProgress(int, java.lang.String, int, int) ,public void setQueryStatistics(boolean) ,public void setQueryStatisticsMaxEntries(int) ,public void setReadOnly(boolean) ,public void setRunMode(com.lealone.db.RunMode) ,public synchronized void shutdownImmediately() ,public HashMap<java.lang.String,java.lang.Integer> statisticsEnd() ,public void statisticsStart() ,public void tryAddMeta(com.lealone.db.session.ServerSession, com.lealone.db.DbObject) ,public com.lealone.db.lock.DbObjectLock tryExclusiveAuthLock(com.lealone.db.session.ServerSession) ,public com.lealone.db.lock.DbObjectLock tryExclusiveCommentLock(com.lealone.db.session.ServerSession) ,public com.lealone.db.lock.DbObjectLock tryExclusiveDatabaseLock(com.lealone.db.session.ServerSession) ,public com.lealone.db.lock.DbObjectLock tryExclusivePluginLock(com.lealone.db.session.ServerSession) ,public com.lealone.db.lock.DbObjectLock tryExclusiveSchemaLock(com.lealone.db.session.ServerSession) ,public com.lealone.db.result.Row tryLockDbObject(com.lealone.db.session.ServerSession, com.lealone.db.DbObject, int) ,public void tryRemoveMeta(com.lealone.db.session.ServerSession, com.lealone.db.schema.SchemaObject, com.lealone.db.lock.DbObjectLock) ,public boolean updateDbSettings(com.lealone.db.session.ServerSession, Map<java.lang.String,java.lang.String>) ,public void updateMeta(com.lealone.db.session.ServerSession, com.lealone.db.DbObject) ,public void updateMeta(com.lealone.db.session.ServerSession, com.lealone.db.DbObject, com.lealone.db.result.Row) ,public void updateMetaAndFirstLevelChildren(com.lealone.db.session.ServerSession, com.lealone.db.DbObject) ,public boolean validateFilePasswordHash(java.lang.String, byte[]) <variables>private static final java.lang.String SYSTEM_USER_NAME,private final com.lealone.db.lock.DbObjectLock authLock,private int closeDelay,private java.lang.Thread closeOnExitHook,private final com.lealone.db.lock.DbObjectLock commentsLock,private com.lealone.db.value.CompareMode compareMode,private com.lealone.db.util.SourceCompiler compiler,private final ConcurrentHashMap<java.lang.Integer,com.lealone.db.DataHandler> dataHandlers,private final com.lealone.db.lock.DbObjectLock databasesLock,private final com.lealone.db.TransactionalDbObjects[] dbObjectsArray,private volatile com.lealone.db.DbSettings dbSettings,private com.lealone.db.api.DatabaseEventListener eventListener,private com.lealone.db.session.ServerSession exclusiveSession,private java.lang.String[] hostIds,private com.lealone.db.schema.Schema infoSchema,private volatile boolean infoSchemaMetaTablesInitialized,private com.lealone.db.ConnectionInfo lastConnectionInfo,private long lastGcMetaId,private long lastSessionRemovedAt,private com.lealone.storage.lob.LobStorage lobStorage,private com.lealone.db.schema.Schema mainSchema,private com.lealone.db.table.Table meta,private com.lealone.db.index.Index metaIdIndex,private java.lang.String metaStorageEngineName,private com.lealone.db.Mode mode,private final java.util.concurrent.atomic.AtomicLong modificationDataId,private final java.util.concurrent.atomic.AtomicLong modificationMetaId,private int nextSessionId,private HashSet<com.lealone.net.NetNode> nodes,private final com.lealone.common.util.BitField objectIds,private final non-sealed Map<java.lang.String,java.lang.String> parameters,private com.lealone.db.schema.Schema perfSchema,private final non-sealed boolean persistent,private final com.lealone.db.lock.DbObjectLock pluginsLock,private com.lealone.db.auth.Role publicRole,private com.lealone.db.stat.QueryStatisticsData queryStatisticsData,private boolean readOnly,private com.lealone.db.RunMode runMode,private final com.lealone.db.scheduler.SchedulerLock schedulerLock,private final com.lealone.db.lock.DbObjectLock schemasLock,private final non-sealed com.lealone.sql.SQLEngine sqlEngine,private volatile com.lealone.db.Database.State state,private final non-sealed java.lang.String storagePath,private final ConcurrentHashMap<java.lang.String,com.lealone.storage.Storage> storages,private com.lealone.db.session.ServerSession systemSession,private com.lealone.db.auth.User systemUser,private final com.lealone.db.table.TableAlterHistory tableAlterHistory,private java.lang.String targetNodes,private final com.lealone.common.util.TempFileDeleter tempFileDeleter,private com.lealone.common.trace.Trace trace,private com.lealone.common.trace.TraceSystem traceSystem,private final non-sealed com.lealone.transaction.TransactionEngine transactionEngine,private final Set<com.lealone.db.session.ServerSession> userSessions,private LinkedList<com.lealone.db.session.ServerSession> waitingSessions
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/MetaRecord.java
|
MetaRecord
|
execute
|
class MetaRecord implements Comparable<MetaRecord> {
public static Row getRow(Table metaTable, DbObject obj) {
Row Row = metaTable.getTemplateRow();
Row.setValue(0, ValueInt.get(obj.getId()));
Row.setValue(1, ValueInt.get(obj.getType().value));
Row.setValue(2, ValueString.get(obj.getCreateSQL()));
return Row;
}
private final int id;
private final DbObjectType objectType;
private final String sql;
public MetaRecord(SearchRow r) {
id = r.getValue(0).getInt();
objectType = DbObjectType.TYPES[r.getValue(1).getInt()];
sql = r.getValue(2).getString();
}
public int getId() {
return id;
}
/**
* Execute the meta data statement.
*
* @param db the database
* @param systemSession the system session
* @param listener the database event listener
*/
public void execute(Database db, ServerSession systemSession, DatabaseEventListener listener) {
execute(db, systemSession, listener, sql, id);
}
public static void execute(Database db, ServerSession systemSession, DatabaseEventListener listener,
String sql, int id) {<FILL_FUNCTION_BODY>}
/**
* Sort the list of meta records by 'create order'.
*
* @param other the other record
* @return -1, 0, or 1
*/
@Override
public int compareTo(MetaRecord other) {
int c1 = objectType.createOrder;
int c2 = other.objectType.createOrder;
if (c1 != c2) {
return c1 - c2;
}
return getId() - other.getId();
}
@Override
public String toString() {
return "MetaRecord [id=" + id + ", objectType=" + objectType + ", sql=" + sql + "]";
}
}
|
try {
PreparedSQLStatement command = systemSession.prepareStatementLocal(sql);
// 设置好数据库对象id,这样在执行create语句创建数据库对象时就能复用上一次得到的id了
command.setObjectId(id);
systemSession.executeUpdateLocal(command);
} catch (DbException e) {
e = e.addSQL(sql);
SQLException s = e.getSQLException();
db.getTrace(TraceModuleType.DATABASE).error(s, sql);
if (listener != null) {
listener.exceptionThrown(s, sql);
// continue startup in this case
} else {
throw e;
}
}
| 523
| 177
| 700
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/PluginObject.java
|
PluginObject
|
getCreateSQL
|
class PluginObject extends DbObjectBase {
private final String implementBy;
private final String classPath;
private final CaseInsensitiveMap<String> parameters;
private Plugin plugin;
private URLClassLoader classLoader;
private String state = "inited";
public PluginObject(Database database, int id, String pluginName, String implementBy,
String classPath, CaseInsensitiveMap<String> parameters) {
super(database, id, pluginName);
this.implementBy = implementBy;
this.classPath = classPath;
this.parameters = parameters;
}
@Override
public DbObjectType getType() {
return DbObjectType.PLUGIN;
}
public Plugin getPlugin() {
return plugin;
}
public void setPlugin(Plugin plugin) {
this.plugin = plugin;
}
public URLClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(URLClassLoader classLoader) {
this.classLoader = classLoader;
}
public void close() {
plugin.close();
if (classLoader != null) {
try {
classLoader.close();
} catch (IOException e) {
}
}
}
@Override
public String getCreateSQL() {<FILL_FUNCTION_BODY>}
public void start() {
plugin.start();
state = "started";
}
public void stop() {
plugin.stop();
state = "stopped";
}
public String getState() {
return state;
}
}
|
StatementBuilder sql = new StatementBuilder("CREATE PLUGIN ");
sql.append("IF NOT EXISTS ");
sql.append(getSQL());
sql.append(" IMPLEMENT BY '").append(implementBy).append("'");
if (classPath != null) {
sql.append(" CLASS PATH '").append(classPath).append("'");
}
if (parameters != null && !parameters.isEmpty()) {
sql.append(" PARAMETERS");
Database.appendMap(sql, parameters);
}
return sql.toString();
| 419
| 142
| 561
|
<methods>public void checkRename() ,public List<? extends com.lealone.db.DbObject> getChildren() ,public java.lang.String getComment() ,public com.lealone.db.Database getDatabase() ,public java.lang.String getDropSQL() ,public int getId() ,public long getModificationId() ,public java.lang.String getName() ,public java.lang.String getSQL() ,public void invalidate() ,public boolean isTemporary() ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public void rename(java.lang.String) ,public void setComment(java.lang.String) ,public void setDatabase(com.lealone.db.Database) ,public void setModified() ,public void setTemporary(boolean) ,public java.lang.String toString() <variables>protected java.lang.String comment,protected com.lealone.db.Database database,protected int id,protected long modificationId,protected java.lang.String name,protected boolean temporary
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/TransactionalDbObjects.java
|
TransactionalDbObjects
|
find
|
class TransactionalDbObjects {
private HashMap<String, DbObject> dbObjects;
private TransactionalDbObjects old;
private long version;
private boolean needGc;
public TransactionalDbObjects() {
this.dbObjects = new CaseInsensitiveMap<>();
}
public HashMap<String, DbObject> getDbObjects() {
return dbObjects;
}
public boolean containsKey(ServerSession session, String dbObjectName) {
return find(session, dbObjectName) != null;
}
public DbObject find(ServerSession session, String dbObjectName) {<FILL_FUNCTION_BODY>}
public void add(DbObject dbObject) {
dbObjects.put(dbObject.getName(), dbObject);
}
public void copyOnAdd(ServerSession session, DbObject dbObject) {
copy(session);
add(dbObject);
}
public void remove(String dbObjectName) {
dbObjects.remove(dbObjectName);
}
public void copyOnRemove(ServerSession session, String dbObjectName) {
copy(session);
remove(dbObjectName);
}
private void copy(ServerSession session) {
long tid = session.getTransaction().getTransactionId();
// 如果是当前事务就不需要重复copy了
if (version != tid) {
TransactionalDbObjects old = new TransactionalDbObjects();
old.dbObjects.putAll(dbObjects);
old.old = this.old;
this.old = old;
version = tid;
}
}
public void commit() {
if (old != null) {
old.version = version;
}
version = 0;
needGc = true;
}
public void rollback() {
if (old != null) {
dbObjects = old.dbObjects;
old = old.old;
}
version = 0;
needGc = true;
}
public void gc(TransactionEngine te) {
if (!needGc)
return;
if (old == null)
return;
if (!te.containsRepeatableReadTransactions()) {
old = null;
return;
}
long minTid = Long.MAX_VALUE;
for (Transaction t : te.currentTransactions()) {
if (t.isRepeatableRead() && t.getTransactionId() < minTid)
minTid = t.getTransactionId();
}
if (minTid != Long.MAX_VALUE) {
TransactionalDbObjects last = this;
TransactionalDbObjects old = this.old;
while (old != null) {
if (old.version < minTid) {
last.old = null;
break;
}
last = old;
old = old.old;
}
} else {
old = null;
}
}
}
|
if (session == null) {
if (version <= 0)
return dbObjects.get(dbObjectName);
else if (old != null) {
return old.find(session, dbObjectName);
} else {
return dbObjects.get(dbObjectName);
}
}
Transaction transaction = session.getTransaction();
long tid = transaction.getTransactionId();
if (tid == version) {
return dbObjects.get(dbObjectName);
}
Transaction pt = transaction.getParentTransaction();
if (pt != null && pt.getTransactionId() == version) {
return dbObjects.get(dbObjectName);
}
switch (transaction.getIsolationLevel()) {
case Transaction.IL_REPEATABLE_READ:
case Transaction.IL_SERIALIZABLE:
if (tid >= version)
return dbObjects.get(dbObjectName);
else if (old != null) {
return old.find(session, dbObjectName);
}
return dbObjects.get(dbObjectName);
case Transaction.IL_READ_COMMITTED:
if (version <= 0)
return dbObjects.get(dbObjectName);
else if (old != null) {
return old.find(session, dbObjectName);
}
default:
return dbObjects.get(dbObjectName);
}
| 760
| 356
| 1,116
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/auth/PasswordHash.java
|
PasswordHash
|
setPasswordLealone
|
class PasswordHash {
public static void setPassword(User user, String password) {
setPasswordLealone(user, password);
setPasswordMongo(user, password);
setPasswordMySQL(user, password);
setPasswordPostgreSQL(user, password);
}
private static void setPasswordLealone(User user, String password) {<FILL_FUNCTION_BODY>}
private static void setPasswordMongo(User user, String password) {
ScramPasswordHash.setPasswordMongo(user, password);
}
private static void setPasswordMySQL(User user, String password) {
if (password == null || password.isEmpty()) {
user.setSaltAndHashMySQL(new byte[0], new byte[0]);
return;
}
byte[] hash = sha1(password);
user.setSaltAndHashMySQL(new byte[0], hash);
}
private static void setPasswordPostgreSQL(User user, String password) {
user.setSaltAndHashPostgreSQL(user.getSalt(), user.getPasswordHash());
}
private static MessageDigest getMessageDigest() {
try {
return MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw DbException.convert(e);
}
}
private static byte[] sha1(String pass) {
MessageDigest md = getMessageDigest();
return md.digest(pass.getBytes());
}
public static boolean validateUserPasswordHash(User user, byte[] userPasswordHash, byte[] salt,
Mode mode) {
if (mode.isMongo())
return validateUserPasswordHashMongo(user, userPasswordHash, salt);
else if (mode.isMySQL())
return validateUserPasswordHashMySQL(user, userPasswordHash, salt);
else if (mode.isPostgreSQL())
return validateUserPasswordHashPostgreSQL(user, userPasswordHash, salt);
else
return validateUserPasswordHashLealone(user, userPasswordHash, salt);
}
private static boolean validateUserPasswordHashLealone(User user, byte[] userPasswordHash,
byte[] salt) {
if (userPasswordHash.length == 0 && user.getPasswordHash().length == 0) {
return true;
}
if (userPasswordHash.length == 0) {
userPasswordHash = SHA256.getKeyPasswordHash(user.getName(), new char[0]);
}
if (salt == null)
salt = user.getSalt();
byte[] hash = SHA256.getHashWithSalt(userPasswordHash, salt);
return Utils.compareSecure(hash, user.getPasswordHash());
}
private static boolean validateUserPasswordHashMongo(User user, byte[] userPasswordHash,
byte[] salt) {
if (userPasswordHash.length == 0 && user.getPasswordHashMongo().length == 0) {
return true;
}
return true;
}
private static boolean validateUserPasswordHashMySQL(User user, byte[] userPasswordHash,
byte[] salt) {
if (userPasswordHash.length == 0 && user.getPasswordHashMySQL().length == 0) {
return true;
}
if (userPasswordHash.length != user.getPasswordHashMySQL().length) {
return false;
}
byte[] hash = scramble411Sha1Pass(user.getPasswordHashMySQL(), salt);
return Utils.compareSecure(userPasswordHash, hash);
}
private static boolean validateUserPasswordHashPostgreSQL(User user, byte[] userPasswordHash,
byte[] salt) {
if (userPasswordHash.length == 0 && user.getPasswordHashPostgreSQL().length == 0) {
return true;
}
if (userPasswordHash.length == 0) {
userPasswordHash = SHA256.getKeyPasswordHash(user.getName(), new char[0]);
}
if (salt == null)
salt = user.getSaltPostgreSQL();
byte[] hash = SHA256.getHashWithSalt(userPasswordHash, salt);
return Utils.compareSecure(hash, user.getPasswordHashPostgreSQL());
}
public static byte[] scramble411Sha1Pass(byte[] sha1Pass, byte[] seed) {
MessageDigest md = getMessageDigest();
byte[] pass2 = md.digest(sha1Pass);
md.reset();
md.update(seed);
byte[] pass3 = md.digest(pass2);
for (int i = 0; i < pass3.length; i++) {
pass3[i] = (byte) (sha1Pass[i] ^ pass3[i]);
}
return pass3;
}
}
|
char[] passwordChars = password == null ? new char[0] : password.toCharArray();
byte[] userPasswordHash = ConnectionInfo.createUserPasswordHash(user.getName(), passwordChars);
user.setUserPasswordHash(userPasswordHash);
| 1,208
| 64
| 1,272
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/auth/Right.java
|
Right
|
getRights
|
class Right extends DbObjectBase {
/**
* The right bit mask that means: selecting from a table is allowed.
*/
public static final int SELECT = 1;
/**
* The right bit mask that means: deleting rows from a table is allowed.
*/
public static final int DELETE = 2;
/**
* The right bit mask that means: inserting rows into a table is allowed.
*/
public static final int INSERT = 4;
/**
* The right bit mask that means: updating data is allowed.
*/
public static final int UPDATE = 8;
/**
* The right bit mask that means: create/alter/drop schema is allowed.
*/
public static final int ALTER_ANY_SCHEMA = 16;
/**
* The right bit mask that means: execute service is allowed.
*/
public static final int EXECUTE = 32;
/**
* The right bit mask that means: select, insert, update, delete, execute and update
* for this object is allowed.
*/
public static final int ALL = SELECT | DELETE | INSERT | UPDATE | EXECUTE;
/**
* To whom the right is granted.
*/
private RightOwner grantee;
/**
* The granted role, or null if a right was granted.
*/
private Role grantedRole;
/**
* The granted right.
*/
private int grantedRight;
/**
* The object. If the right is global, this is null.
*/
private DbObject grantedObject;
public Right(Database db, int id, RightOwner grantee, Role grantedRole) {
super(db, id, "RIGHT_" + id);
this.grantee = grantee;
this.grantedRole = grantedRole;
}
public Right(Database db, int id, RightOwner grantee, int grantedRight, DbObject grantedObject) {
super(db, id, "" + id);
this.grantee = grantee;
this.grantedRight = grantedRight;
this.grantedObject = grantedObject;
// TODO 如何更优雅的处理临时对象的授权(或者内存数据库中的所有对象的授权)
// grantedObject有可能为null,如: GRANT ALTER ANY SCHEMA
if (grantedObject != null
&& (grantedObject.isTemporary() || !grantedObject.getDatabase().isPersistent()))
setTemporary(true);
}
@Override
public DbObjectType getType() {
return DbObjectType.RIGHT;
}
private static boolean appendRight(StringBuilder buff, int right, int mask, String name,
boolean comma) {
if ((right & mask) != 0) {
if (comma) {
buff.append(", ");
}
buff.append(name);
return true;
}
return comma;
}
public String getRights() {<FILL_FUNCTION_BODY>}
public Role getGrantedRole() {
return grantedRole;
}
public DbObject getGrantedObject() {
return grantedObject;
}
public DbObject getGrantee() {
return grantee;
}
@Override
public String getCreateSQL() {
StringBuilder buff = new StringBuilder();
buff.append("GRANT ");
if (grantedRole != null) {
buff.append(grantedRole.getSQL());
} else {
buff.append(getRights());
if (grantedObject != null) {
if (grantedObject instanceof Schema) {
buff.append(" ON SCHEMA ").append(grantedObject.getSQL());
} else if (grantedObject instanceof Service) {
buff.append(" ON SERVICE ").append(grantedObject.getSQL());
} else if (grantedObject instanceof Table) {
buff.append(" ON ").append(grantedObject.getSQL());
}
}
}
buff.append(" TO ").append(grantee.getSQL());
return buff.toString();
}
@Override
public void removeChildrenAndResources(ServerSession session, DbObjectLock lock) {
if (grantedRole != null) {
grantee.revokeRole(grantedRole);
} else {
grantee.revokeRight(grantedObject);
}
super.removeChildrenAndResources(session, lock);
}
@Override
public void invalidate() {
grantedRole = null;
grantedObject = null;
grantee = null;
super.invalidate();
}
@Override
public void checkRename() {
DbException.throwInternalError();
}
public void setRightMask(int rightMask) {
grantedRight = rightMask;
}
public int getRightMask() {
return grantedRight;
}
}
|
StringBuilder buff = new StringBuilder();
if (grantedRight == ALL) {
buff.append("ALL");
} else {
boolean comma = false;
comma = appendRight(buff, grantedRight, SELECT, "SELECT", comma);
comma = appendRight(buff, grantedRight, DELETE, "DELETE", comma);
comma = appendRight(buff, grantedRight, INSERT, "INSERT", comma);
comma = appendRight(buff, grantedRight, EXECUTE, "EXECUTE", comma);
comma = appendRight(buff, grantedRight, ALTER_ANY_SCHEMA, "ALTER ANY SCHEMA", comma);
appendRight(buff, grantedRight, UPDATE, "UPDATE", comma);
}
return buff.toString();
| 1,248
| 184
| 1,432
|
<methods>public void checkRename() ,public List<? extends com.lealone.db.DbObject> getChildren() ,public java.lang.String getComment() ,public com.lealone.db.Database getDatabase() ,public java.lang.String getDropSQL() ,public int getId() ,public long getModificationId() ,public java.lang.String getName() ,public java.lang.String getSQL() ,public void invalidate() ,public boolean isTemporary() ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public void rename(java.lang.String) ,public void setComment(java.lang.String) ,public void setDatabase(com.lealone.db.Database) ,public void setModified() ,public void setTemporary(boolean) ,public java.lang.String toString() <variables>protected java.lang.String comment,protected com.lealone.db.Database database,protected int id,protected long modificationId,protected java.lang.String name,protected boolean temporary
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/auth/RightOwner.java
|
RightOwner
|
isRightGrantedRecursive
|
class RightOwner extends DbObjectBase {
/**
* The map of granted roles.
*/
private HashMap<Role, Right> grantedRoles;
/**
* The map of granted rights.
*/
private HashMap<DbObject, Right> grantedRights;
protected RightOwner(Database database, int id, String name) {
super(database, id, name);
}
/**
* Check if a role has been granted for this right owner.
*
* @param grantedRole the role
* @return true if the role has been granted
*/
public boolean isRoleGranted(Role grantedRole) {
if (grantedRole == this) {
return true;
}
if (grantedRoles != null) {
for (Role role : grantedRoles.keySet()) {
if (role == grantedRole) {
return true;
}
if (role.isRoleGranted(grantedRole)) {
return true;
}
}
}
return false;
}
/**
* Check if a right is already granted to this object or to objects that
* were granted to this object. The rights for schemas takes
* precedence over rights of tables, in other words, the rights of schemas
* will be valid for every each table in the related schema.
*
* @param schemaObject the schema object(table or service) to check
* @param rightMask the right mask to check
* @return true if the right was already granted
*/
boolean isRightGrantedRecursive(SchemaObject schemaObject, int rightMask) {<FILL_FUNCTION_BODY>}
/**
* Grant a right for the given table. Only one right object per table is
* supported.
*
* @param object the object (table or schema)
* @param right the right
*/
public void grantRight(DbObject object, Right right) {
if (grantedRights == null) {
grantedRights = new HashMap<>();
}
grantedRights.put(object, right);
}
/**
* Revoke the right for the given object (table or schema).
*
* @param object the object
*/
void revokeRight(DbObject object) {
if (grantedRights == null) {
return;
}
grantedRights.remove(object);
if (grantedRights.isEmpty()) {
grantedRights = null;
}
}
/**
* Grant a role to this object.
*
* @param role the role
* @param right the right to grant
*/
public void grantRole(Role role, Right right) {
if (grantedRoles == null) {
grantedRoles = new HashMap<>();
}
grantedRoles.put(role, right);
}
/**
* Remove the right for the given role.
*
* @param role the role to revoke
*/
void revokeRole(Role role) {
if (grantedRoles == null) {
return;
}
Right right = grantedRoles.get(role);
if (right == null) {
return;
}
grantedRoles.remove(role);
if (grantedRoles.isEmpty()) {
grantedRoles = null;
}
}
/**
* Get the 'grant schema' right of this object.
*
* @param object the granted object (table or schema)
* @return the right or null if the right has not been granted
*/
public Right getRightForObject(DbObject object) {
if (grantedRights == null) {
return null;
}
return grantedRights.get(object);
}
/**
* Get the 'grant role' right of this object.
*
* @param role the granted role
* @return the right or null if the right has not been granted
*/
public Right getRightForRole(Role role) {
if (grantedRoles == null) {
return null;
}
return grantedRoles.get(role);
}
}
|
Right right;
if (grantedRights != null) {
if (schemaObject != null) {
right = grantedRights.get(schemaObject.getSchema());
if (right != null) {
if ((right.getRightMask() & rightMask) == rightMask) {
return true;
}
}
}
right = grantedRights.get(schemaObject);
if (right != null) {
if ((right.getRightMask() & rightMask) == rightMask) {
return true;
}
}
}
if (grantedRoles != null) {
for (RightOwner role : grantedRoles.keySet()) {
if (role.isRightGrantedRecursive(schemaObject, rightMask)) {
return true;
}
}
}
return false;
| 1,047
| 216
| 1,263
|
<methods>public void checkRename() ,public List<? extends com.lealone.db.DbObject> getChildren() ,public java.lang.String getComment() ,public com.lealone.db.Database getDatabase() ,public java.lang.String getDropSQL() ,public int getId() ,public long getModificationId() ,public java.lang.String getName() ,public java.lang.String getSQL() ,public void invalidate() ,public boolean isTemporary() ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public void rename(java.lang.String) ,public void setComment(java.lang.String) ,public void setDatabase(com.lealone.db.Database) ,public void setModified() ,public void setTemporary(boolean) ,public java.lang.String toString() <variables>protected java.lang.String comment,protected com.lealone.db.Database database,protected int id,protected long modificationId,protected java.lang.String name,protected boolean temporary
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/auth/Role.java
|
Role
|
removeChildrenAndResources
|
class Role extends RightOwner {
private final boolean system;
public Role(Database database, int id, String roleName, boolean system) {
super(database, id, roleName);
this.system = system;
}
@Override
public DbObjectType getType() {
return DbObjectType.ROLE;
}
/**
* Get the CREATE SQL statement for this object.
*
* @param ifNotExists true if IF NOT EXISTS should be used
* @return the SQL statement
*/
public String getCreateSQL(boolean ifNotExists) {
if (system) {
return null;
}
StringBuilder buff = new StringBuilder("CREATE ROLE ");
if (ifNotExists) {
buff.append("IF NOT EXISTS ");
}
buff.append(getSQL());
return buff.toString();
}
@Override
public String getCreateSQL() {
return getCreateSQL(false);
}
@Override
public void removeChildrenAndResources(ServerSession session, DbObjectLock lock) {<FILL_FUNCTION_BODY>}
}
|
for (User user : database.getAllUsers()) {
Right right = user.getRightForRole(this);
if (right != null) {
database.removeDatabaseObject(session, right, lock);
}
}
for (Role r2 : database.getAllRoles()) {
Right right = r2.getRightForRole(this);
if (right != null) {
database.removeDatabaseObject(session, right, lock);
}
}
for (Right right : database.getAllRights()) {
if (right.getGrantee() == this) {
database.removeDatabaseObject(session, right, lock);
}
}
super.removeChildrenAndResources(session, lock);
| 287
| 185
| 472
|
<methods>public com.lealone.db.auth.Right getRightForObject(com.lealone.db.DbObject) ,public com.lealone.db.auth.Right getRightForRole(com.lealone.db.auth.Role) ,public void grantRight(com.lealone.db.DbObject, com.lealone.db.auth.Right) ,public void grantRole(com.lealone.db.auth.Role, com.lealone.db.auth.Right) ,public boolean isRoleGranted(com.lealone.db.auth.Role) <variables>private HashMap<com.lealone.db.DbObject,com.lealone.db.auth.Right> grantedRights,private HashMap<com.lealone.db.auth.Role,com.lealone.db.auth.Right> grantedRoles
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/auth/scram/ScramPasswordHash.java
|
ScramPasswordHash
|
generateSaltedPassword
|
class ScramPasswordHash {
public static void setPasswordMongo(User user, String password) {
setPasswordMongo(user, password, 256);
}
public static void setPasswordMongo(User user, String password, int mechanism) {
try {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[24];
random.nextBytes(salt);
if (mechanism == 1)
password = createAuthenticationHash(user.getName(), password.toCharArray());
byte[] saltedPassword = generateSaltedPassword(password, salt, 4096, "HmacSHA" + mechanism);
user.setSaltAndHashMongo(salt, saltedPassword);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw DbException.convert(e);
}
}
public static ScramPasswordData createScramPasswordData(byte[] salt, byte[] saltedPassword,
int mechanism) {
try {
return newPassword(salt, saltedPassword, 4096, "SHA-" + mechanism, "HmacSHA" + mechanism);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw DbException.convert(e);
}
}
private static ScramPasswordData newPassword(byte[] salt, byte[] saltedPassword, int iterations,
String digestName, String hmacName) throws NoSuchAlgorithmException, InvalidKeyException {
if (!hmacName.toLowerCase().startsWith("hmac")) {
throw new IllegalArgumentException("Invalid HMAC: " + hmacName);
}
if (saltedPassword.length == 0)
return new ScramPasswordData(salt, saltedPassword, saltedPassword, saltedPassword,
iterations);
byte[] clientKey = computeHmac(saltedPassword, hmacName, "Client Key");
byte[] storedKey = MessageDigest.getInstance(digestName).digest(clientKey);
byte[] serverKey = computeHmac(saltedPassword, hmacName, "Server Key");
return new ScramPasswordData(salt, saltedPassword, storedKey, serverKey, iterations);
}
private static final byte[] INT_1 = new byte[] { 0, 0, 0, 1 };
private static byte[] generateSaltedPassword(String password, byte[] salt, int iterations,
String hmacName) throws InvalidKeyException, NoSuchAlgorithmException {<FILL_FUNCTION_BODY>}
// 这是MongoDB使用SCRAM-SHA-1时的特殊格式
private static String createAuthenticationHash(String userName, char[] password) {
ByteArrayOutputStream bout = new ByteArrayOutputStream(userName.length() + 20 + password.length);
try {
bout.write(userName.getBytes(StandardCharsets.UTF_8));
bout.write(":mongo:".getBytes(StandardCharsets.UTF_8));
bout.write(new String(password).getBytes(StandardCharsets.UTF_8));
} catch (IOException ioe) {
throw new RuntimeException("impossible", ioe);
}
return hexMD5(bout.toByteArray());
}
private static String hexMD5(byte[] data) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(data);
byte[] digest = md5.digest();
return toHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Error - this implementation of Java doesn't support MD5.");
}
}
private static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
String s = Integer.toHexString(0xff & b);
if (s.length() < 2) {
sb.append("0");
}
sb.append(s);
}
return sb.toString();
}
private static Mac createHmac(byte[] keyBytes, String hmacName)
throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec key = new SecretKeySpec(keyBytes, hmacName);
Mac mac = Mac.getInstance(hmacName);
mac.init(key);
return mac;
}
public static byte[] computeHmac(byte[] key, String hmacName, String string)
throws InvalidKeyException, NoSuchAlgorithmException {
Mac mac = createHmac(key, hmacName);
mac.update(string.getBytes(StandardCharsets.US_ASCII));
return mac.doFinal();
}
}
|
if (password.isEmpty())
return new byte[0];
Mac mac = createHmac(password.getBytes(StandardCharsets.US_ASCII), hmacName);
mac.update(salt);
mac.update(INT_1);
byte[] result = mac.doFinal();
byte[] previous = null;
for (int i = 1; i < iterations; i++) {
mac.update(previous != null ? previous : result);
previous = mac.doFinal();
for (int x = 0; x < result.length; x++) {
result[x] ^= previous[x];
}
}
return result;
| 1,189
| 170
| 1,359
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/constraint/Constraint.java
|
Constraint
|
compareTo
|
class Constraint extends SchemaObjectBase implements Comparable<Constraint> {
/**
* The constraint type name for check constraints.
*/
public static final String CHECK = "CHECK";
/**
* The constraint type name for referential constraints.
*/
public static final String REFERENTIAL = "REFERENTIAL";
/**
* The constraint type name for unique constraints.
*/
public static final String UNIQUE = "UNIQUE";
/**
* The constraint type name for primary key constraints.
*/
public static final String PRIMARY_KEY = "PRIMARY KEY";
/**
* The table for which this constraint is defined.
*/
protected Table table;
Constraint(Schema schema, int id, String name, Table table) {
super(schema, id, name);
this.table = table;
this.setTemporary(table.isTemporary());
}
@Override
public DbObjectType getType() {
return DbObjectType.CONSTRAINT;
}
/**
* The constraint type name
*
* @return the name
*/
public abstract String getConstraintType();
/**
* Check if this row fulfils the constraint.
* This method throws an exception if not.
*
* @param session the session
* @param t the table
* @param oldRow the old row
* @param newRow the new row
*/
public abstract void checkRow(ServerSession session, Table t, Row oldRow, Row newRow);
/**
* Check if this constraint needs the specified index.
*
* @param index the index
* @return true if the index is used
*/
public abstract boolean usesIndex(Index index);
/**
* This index is now the owner of the specified index.
*
* @param index the index
*/
public abstract void setIndexOwner(Index index);
/**
* Get all referenced columns.
*
* @param table the table
* @return the set of referenced columns
*/
public abstract HashSet<Column> getReferencedColumns(Table table);
/**
* Get the SQL statement to create this constraint.
*
* @return the SQL statement
*/
public abstract String getCreateSQLWithoutIndexes();
/**
* Check if this constraint needs to be checked before updating the data.
*
* @return true if it must be checked before updating
*/
public abstract boolean isBefore();
/**
* Check the existing data. This method is called if the constraint is added
* after data has been inserted into the table.
*
* @param session the session
*/
public abstract void checkExistingData(ServerSession session);
/**
* This method is called after a related table has changed
* (the table was renamed, or columns have been renamed).
*/
public abstract void rebuild();
/**
* Get the unique index used to enforce this constraint, or null if no index
* is used.
*
* @return the index
*/
public abstract Index getUniqueIndex();
public Table getTable() {
return table;
}
public Table getRefTable() {
return table;
}
private int getConstraintTypeOrder() {
String constraintType = getConstraintType();
if (CHECK.equals(constraintType)) {
return 0;
} else if (PRIMARY_KEY.equals(constraintType)) {
return 1;
} else if (UNIQUE.equals(constraintType)) {
return 2;
} else if (REFERENTIAL.equals(constraintType)) {
return 3;
} else {
throw DbException.getInternalError("type: " + constraintType);
}
}
@Override
public int compareTo(Constraint other) {<FILL_FUNCTION_BODY>}
@Override
public boolean isHidden() {
return table.isHidden();
}
public void getDependencies(Set<DbObject> dependencies) {
}
}
|
if (this == other) {
return 0;
}
int thisType = getConstraintTypeOrder();
int otherType = other.getConstraintTypeOrder();
return thisType - otherType;
| 1,028
| 54
| 1,082
|
<methods>public java.lang.String getSQL() ,public com.lealone.db.schema.Schema getSchema() ,public boolean isHidden() <variables>protected final non-sealed com.lealone.db.schema.Schema schema
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/constraint/ConstraintCheck.java
|
ConstraintCheck
|
getCreateSQL
|
class ConstraintCheck extends Constraint {
private IExpression.Evaluator exprEvaluator;
private IExpression expr;
public ConstraintCheck(Schema schema, int id, String name, Table table) {
super(schema, id, name, table);
}
@Override
public String getConstraintType() {
return Constraint.CHECK;
}
public void setExpressionEvaluator(IExpression.Evaluator exprEvaluator) {
this.exprEvaluator = exprEvaluator;
}
public void setExpression(IExpression expr) {
this.expr = expr;
}
private String getShortDescription() {
return getName() + ": " + expr.getSQL();
}
@Override
public String getCreateSQLWithoutIndexes() {
return getCreateSQL();
}
@Override
public String getCreateSQL() {<FILL_FUNCTION_BODY>}
@Override
public void removeChildrenAndResources(ServerSession session, DbObjectLock lock) {
table.removeConstraint(this);
}
@Override
public void checkRow(ServerSession session, Table t, Row oldRow, Row newRow) {
if (newRow == null) {
return;
}
Value v;
try {
synchronized (this) {
// 这里要同步,多个事务会把exprEvaluator的值修改
v = exprEvaluator.getExpressionValue(session, expr, newRow);
}
} catch (DbException ex) {
throw DbException.get(ErrorCode.CHECK_CONSTRAINT_INVALID, ex, getShortDescription());
}
// Both TRUE and NULL are ok
if (v.isFalse()) {
throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1, getShortDescription());
}
}
@Override
public boolean usesIndex(Index index) {
return false;
}
@Override
public void setIndexOwner(Index index) {
DbException.throwInternalError();
}
@Override
public HashSet<Column> getReferencedColumns(Table table) {
HashSet<Column> columns = new HashSet<>();
expr.getColumns(columns);
for (Iterator<Column> it = columns.iterator(); it.hasNext();) {
if (it.next().getTable() != table) {
it.remove();
}
}
return columns;
}
public IExpression getExpression() {
return expr;
}
@Override
public boolean isBefore() {
return true;
}
@Override
public void checkExistingData(ServerSession session) {
if (session.getDatabase().isStarting()) {
// don't check at startup
return;
}
String sql = "SELECT 1 FROM " + table.getSQL() + " WHERE NOT(" + expr.getSQL() + ")";
Result r = session.executeNestedQueryLocal(sql);
if (r.next()) {
throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1, getName());
}
}
@Override
public Index getUniqueIndex() {
return null;
}
@Override
public void rebuild() {
// nothing to do
}
@Override
public void getDependencies(Set<DbObject> dependencies) {
expr.getDependencies(dependencies);
}
}
|
StringBuilder buff = new StringBuilder("ALTER TABLE ");
buff.append(table.getSQL()).append(" ADD CONSTRAINT ");
if (table.isHidden()) {
buff.append("IF NOT EXISTS ");
}
buff.append(getSQL());
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
buff.append(" CHECK").append(StringUtils.enclose(expr.getSQL())).append(" NOCHECK");
return buff.toString();
| 902
| 136
| 1,038
|
<methods>public abstract void checkExistingData(com.lealone.db.session.ServerSession) ,public abstract void checkRow(com.lealone.db.session.ServerSession, com.lealone.db.table.Table, com.lealone.db.result.Row, com.lealone.db.result.Row) ,public int compareTo(com.lealone.db.constraint.Constraint) ,public abstract java.lang.String getConstraintType() ,public abstract java.lang.String getCreateSQLWithoutIndexes() ,public void getDependencies(Set<com.lealone.db.DbObject>) ,public com.lealone.db.table.Table getRefTable() ,public abstract HashSet<com.lealone.db.table.Column> getReferencedColumns(com.lealone.db.table.Table) ,public com.lealone.db.table.Table getTable() ,public com.lealone.db.DbObjectType getType() ,public abstract com.lealone.db.index.Index getUniqueIndex() ,public abstract boolean isBefore() ,public boolean isHidden() ,public abstract void rebuild() ,public abstract void setIndexOwner(com.lealone.db.index.Index) ,public abstract boolean usesIndex(com.lealone.db.index.Index) <variables>public static final java.lang.String CHECK,public static final java.lang.String PRIMARY_KEY,public static final java.lang.String REFERENTIAL,public static final java.lang.String UNIQUE,protected com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/constraint/ConstraintUnique.java
|
ConstraintUnique
|
getReferencedColumns
|
class ConstraintUnique extends Constraint {
private Index index;
private boolean indexOwner;
private IndexColumn[] columns;
private final boolean primaryKey;
public ConstraintUnique(Schema schema, int id, String name, Table table, boolean primaryKey) {
super(schema, id, name, table);
this.primaryKey = primaryKey;
}
@Override
public String getConstraintType() {
return primaryKey ? Constraint.PRIMARY_KEY : Constraint.UNIQUE;
}
private String getCreateSQLForCopy(Table forTable, String quotedName, boolean internalIndex) {
StatementBuilder buff = new StatementBuilder("ALTER TABLE ");
buff.append(forTable.getSQL()).append(" ADD CONSTRAINT ");
if (forTable.isHidden()) {
buff.append("IF NOT EXISTS ");
}
buff.append(quotedName);
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
buff.append(' ').append(getTypeName()).append('(');
for (IndexColumn c : columns) {
buff.appendExceptFirst(", ");
buff.append(forTable.getDatabase().quoteIdentifier(c.column.getName()));
}
buff.append(')');
if (internalIndex && indexOwner && forTable == this.table) {
buff.append(" INDEX ").append(index.getSQL());
}
return buff.toString();
}
private String getTypeName() {
if (primaryKey) {
return "PRIMARY KEY";
}
return "UNIQUE";
}
@Override
public String getCreateSQLWithoutIndexes() {
return getCreateSQLForCopy(table, getSQL(), false);
}
@Override
public String getCreateSQL() {
return getCreateSQLForCopy(table, getSQL(), true);
}
public void setColumns(IndexColumn[] columns) {
this.columns = columns;
}
public IndexColumn[] getColumns() {
return columns;
}
/**
* Set the index to use for this unique constraint.
*
* @param index the index
* @param isOwner true if the index is generated by the system and belongs
* to this constraint
*/
public void setIndex(Index index, boolean isOwner) {
this.index = index;
this.indexOwner = isOwner;
}
@Override
public void removeChildrenAndResources(ServerSession session, DbObjectLock lock) {
table.removeConstraint(this);
if (indexOwner) {
table.removeIndexOrTransferOwnership(session, index, lock);
}
}
@Override
public void invalidate() {
index = null;
columns = null;
table = null;
super.invalidate();
}
@Override
public void checkRow(ServerSession session, Table t, Row oldRow, Row newRow) {
// unique index check is enough
}
@Override
public boolean usesIndex(Index idx) {
return idx == index;
}
@Override
public void setIndexOwner(Index index) {
indexOwner = true;
}
@Override
public HashSet<Column> getReferencedColumns(Table table) {<FILL_FUNCTION_BODY>}
@Override
public boolean isBefore() {
return true;
}
@Override
public void checkExistingData(ServerSession session) {
// no need to check: when creating the unique index any problems are
// found
}
@Override
public Index getUniqueIndex() {
return index;
}
@Override
public void rebuild() {
// nothing to do
}
}
|
HashSet<Column> result = new HashSet<>(columns.length);
for (IndexColumn c : columns) {
result.add(c.column);
}
return result;
| 964
| 50
| 1,014
|
<methods>public abstract void checkExistingData(com.lealone.db.session.ServerSession) ,public abstract void checkRow(com.lealone.db.session.ServerSession, com.lealone.db.table.Table, com.lealone.db.result.Row, com.lealone.db.result.Row) ,public int compareTo(com.lealone.db.constraint.Constraint) ,public abstract java.lang.String getConstraintType() ,public abstract java.lang.String getCreateSQLWithoutIndexes() ,public void getDependencies(Set<com.lealone.db.DbObject>) ,public com.lealone.db.table.Table getRefTable() ,public abstract HashSet<com.lealone.db.table.Column> getReferencedColumns(com.lealone.db.table.Table) ,public com.lealone.db.table.Table getTable() ,public com.lealone.db.DbObjectType getType() ,public abstract com.lealone.db.index.Index getUniqueIndex() ,public abstract boolean isBefore() ,public boolean isHidden() ,public abstract void rebuild() ,public abstract void setIndexOwner(com.lealone.db.index.Index) ,public abstract boolean usesIndex(com.lealone.db.index.Index) <variables>public static final java.lang.String CHECK,public static final java.lang.String PRIMARY_KEY,public static final java.lang.String REFERENTIAL,public static final java.lang.String UNIQUE,protected com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/IndexColumn.java
|
IndexColumn
|
getSQL
|
class IndexColumn {
/**
* The column name.
*/
public String columnName;
/**
* The column, or null if not set.
*/
public Column column;
/**
* The sort type. Ascending (the default) and descending are supported;
* nulls can be sorted first or last.
*/
public int sortType = SortOrder.ASCENDING;
/**
* Get the SQL snippet for this index column.
*
* @return the SQL snippet
*/
public String getSQL() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "IndexColumn [" + columnName + "]";
}
/**
* Create an array of index columns from a list of columns. The default sort
* type is used.
*
* @param columns the column list
* @return the index column array
*/
public static IndexColumn[] wrap(Column[] columns) {
IndexColumn[] list = new IndexColumn[columns.length];
for (int i = 0; i < list.length; i++) {
list[i] = new IndexColumn();
list[i].column = columns[i];
}
return list;
}
/**
* Map the columns using the column names and the specified table.
*
* @param indexColumns the column list with column names set
* @param table the table from where to map the column names to columns
*/
public static void mapColumns(IndexColumn[] indexColumns, Table table) {
for (IndexColumn col : indexColumns) {
col.column = table.getColumn(col.columnName);
}
}
}
|
StringBuilder buff = new StringBuilder(column.getSQL());
if ((sortType & SortOrder.DESCENDING) != 0) {
buff.append(" DESC");
}
if ((sortType & SortOrder.NULLS_FIRST) != 0) {
buff.append(" NULLS FIRST");
} else if ((sortType & SortOrder.NULLS_LAST) != 0) {
buff.append(" NULLS LAST");
}
return buff.toString();
| 434
| 126
| 560
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/IndexRebuilder.java
|
IndexRebuilder
|
rebuild
|
class IndexRebuilder implements Runnable {
private final ServerSession session;
private final Table table;
private final Index index;
public IndexRebuilder(ServerSession session, Table table, Index index) {
this.session = session;
this.table = table;
this.index = index;
}
@Override
public void run() {
rebuild();
}
public void rebuild() {<FILL_FUNCTION_BODY>}
}
|
session.setUndoLogEnabled(false);
try {
Index scan = table.getScanIndex(session);
int rowCount = MathUtils.convertLongToInt(scan.getRowCount(session));
long i = 0;
String n = table.getName() + ":" + index.getName();
Database database = table.getSchema().getDatabase();
Cursor cursor = scan.find(session, null, null);
while (cursor.next()) {
Row row = cursor.get();
index.add(session, row);
if ((++i & 127) == 0) {
database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n,
MathUtils.convertLongToInt(i), rowCount);
}
}
} catch (DbException e) {
table.getSchema().freeUniqueName(index.getName());
try {
index.remove(session);
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means
// there is something wrong with the database
session.getTrace().setType(TraceModuleType.TABLE).error(e2, "could not remove index");
throw e2;
}
throw e;
} finally {
session.setUndoLogEnabled(true);
}
| 120
| 338
| 458
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/IndexType.java
|
IndexType
|
createScan
|
class IndexType {
private boolean primaryKey;
private boolean unique;
private boolean hash;
private boolean scan;
private boolean delegate;
private boolean belongsToConstraint;
/**
* Create a primary key index.
*
* @param hash if a hash index should be used
* @return the index type
*/
public static IndexType createPrimaryKey(boolean hash) {
IndexType type = new IndexType();
type.primaryKey = true;
type.hash = hash;
type.unique = true;
return type;
}
public static IndexType createDelegate() {
IndexType type = new IndexType();
type.primaryKey = true;
type.delegate = true;
return type;
}
/**
* Create a unique index.
*
* @param hash if a hash index should be used
* @return the index type
*/
public static IndexType createUnique(boolean hash) {
IndexType type = new IndexType();
type.unique = true;
type.hash = hash;
return type;
}
/**
* Create a non-unique index.
*
* @return the index type
*/
public static IndexType createNonUnique() {
return createNonUnique(false);
}
/**
* Create a non-unique index.
*
* @param hash if a hash index should be used
* @return the index type
*/
public static IndexType createNonUnique(boolean hash) {
IndexType type = new IndexType();
type.hash = hash;
return type;
}
/**
* Create a scan pseudo-index.
*
* @return the index type
*/
public static IndexType createScan() {<FILL_FUNCTION_BODY>}
/**
* Does this index belong to a primary key constraint?
*
* @return true if it references a primary key constraint
*/
public boolean isPrimaryKey() {
return primaryKey;
}
/**
* Is this a unique index?
*
* @return true if it is
*/
public boolean isUnique() {
return unique;
}
/**
* Is this a hash index?
*
* @return true if it is a hash index
*/
public boolean isHash() {
return hash;
}
/**
* Is this a table scan pseudo-index?
*
* @return true if it is
*/
public boolean isScan() {
return scan;
}
public boolean isDelegate() {
return delegate;
}
/**
* Sets if this index belongs to a constraint.
*
* @param belongsToConstraint if the index belongs to a constraint
*/
public void setBelongsToConstraint(boolean belongsToConstraint) {
this.belongsToConstraint = belongsToConstraint;
}
/**
* If the index is created because of a constraint. Such indexes are to be
* dropped once the constraint is dropped.
*
* @return if the index belongs to a constraint
*/
public boolean getBelongsToConstraint() {
return belongsToConstraint;
}
/**
* Get the SQL snippet to create such an index.
*
* @return the SQL snippet
*/
public String getSQL() {
StringBuilder buff = new StringBuilder();
if (primaryKey) {
buff.append("PRIMARY KEY");
if (hash) {
buff.append(" HASH");
}
} else {
if (unique) {
buff.append("UNIQUE ");
}
if (hash) {
buff.append("HASH ");
}
buff.append("INDEX");
}
return buff.toString();
}
}
|
IndexType type = new IndexType();
type.scan = true;
return type;
| 969
| 26
| 995
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/MetaIndex.java
|
MetaIndex
|
getColumnIndex
|
class MetaIndex extends IndexBase {
private final MetaTable meta;
private final boolean scan;
public MetaIndex(MetaTable meta, IndexColumn[] columns, boolean scan) {
super(meta, 0, null, IndexType.createNonUnique(), columns);
this.meta = meta;
this.scan = scan;
}
@Override
public int getColumnIndex(Column col) {<FILL_FUNCTION_BODY>}
@Override
public Cursor find(ServerSession session, SearchRow first, SearchRow last) {
ArrayList<Row> rows = meta.generateRows(session, first, last);
return new MetaCursor(rows);
}
@Override
public double getCost(ServerSession session, int[] masks, SortOrder sortOrder) {
if (scan) {
return 10 * MetaTable.ROW_COUNT_APPROXIMATION;
}
return getCostRangeIndex(masks, MetaTable.ROW_COUNT_APPROXIMATION, sortOrder);
}
@Override
public String getCreateSQL() {
return null;
}
@Override
public long getRowCount(ServerSession session) {
return MetaTable.ROW_COUNT_APPROXIMATION;
}
@Override
public long getRowCountApproximation() {
return MetaTable.ROW_COUNT_APPROXIMATION;
}
@Override
public long getDiskSpaceUsed() {
return meta.getDiskSpaceUsed();
}
@Override
public String getPlanSQL() {
return "meta";
}
/**
* An index for a meta data table.
* This index can only scan through all rows, search is not supported.
*/
private static class MetaCursor implements Cursor {
private final ArrayList<Row> rows;
private Row current;
private int index;
MetaCursor(ArrayList<Row> rows) {
this.rows = rows;
}
@Override
public Row get() {
return current;
}
@Override
public boolean next() {
current = index >= rows.size() ? null : rows.get(index++);
return current != null;
}
}
}
|
if (scan) {
// the scan index cannot use any columns
return -1;
}
return super.getColumnIndex(col);
| 574
| 40
| 614
|
<methods>public boolean canGetFirstOrLast() ,public boolean canScan() ,public void checkRename() ,public void close(com.lealone.db.session.ServerSession) ,public int compareRows(com.lealone.db.result.SearchRow, com.lealone.db.result.SearchRow) ,public com.lealone.db.index.Cursor find(com.lealone.db.session.ServerSession, CursorParameters<com.lealone.db.result.SearchRow>) ,public com.lealone.db.index.Cursor findDistinct(com.lealone.db.session.ServerSession) ,public com.lealone.db.result.SearchRow findFirstOrLast(com.lealone.db.session.ServerSession, boolean) ,public int[] getColumnIds() ,public int getColumnIndex(com.lealone.db.table.Column) ,public com.lealone.db.table.Column[] getColumns() ,public java.lang.String getCreateSQL() ,public long getDiskSpaceUsed() ,public com.lealone.db.index.IndexColumn[] getIndexColumns() ,public com.lealone.db.index.IndexType getIndexType() ,public long getMemorySpaceUsed() ,public java.lang.String getPlanSQL() ,public com.lealone.db.result.Row getRow(com.lealone.db.session.ServerSession, long) ,public com.lealone.db.table.Table getTable() ,public com.lealone.db.DbObjectType getType() ,public boolean isHidden() ,public boolean isInMemory() ,public boolean isRowIdIndex() ,public boolean needRebuild() ,public void remove(com.lealone.db.session.ServerSession) ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public boolean supportsDistinctQuery() ,public void truncate(com.lealone.db.session.ServerSession) <variables>protected int[] columnIds,protected com.lealone.db.table.Column[] columns,protected com.lealone.db.index.IndexColumn[] indexColumns,protected final non-sealed com.lealone.db.index.IndexType indexType,protected final non-sealed com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/RangeIndex.java
|
RangeCursor
|
next
|
class RangeCursor implements Cursor {
private final long start, end, step;
private boolean beforeFirst;
private long current;
private Row currentRow;
RangeCursor(long start, long end, long step) {
this.start = start;
this.end = end;
this.step = step;
beforeFirst = true;
}
@Override
public Row get() {
return currentRow;
}
@Override
public boolean next() {<FILL_FUNCTION_BODY>}
}
|
if (beforeFirst) {
beforeFirst = false;
current = start;
} else {
current += step;
}
currentRow = new Row(new Value[] { ValueLong.get(current) }, 1);
return step > 0 ? current <= end : current >= end;
| 138
| 76
| 214
|
<methods>public boolean canGetFirstOrLast() ,public boolean canScan() ,public void checkRename() ,public void close(com.lealone.db.session.ServerSession) ,public int compareRows(com.lealone.db.result.SearchRow, com.lealone.db.result.SearchRow) ,public com.lealone.db.index.Cursor find(com.lealone.db.session.ServerSession, CursorParameters<com.lealone.db.result.SearchRow>) ,public com.lealone.db.index.Cursor findDistinct(com.lealone.db.session.ServerSession) ,public com.lealone.db.result.SearchRow findFirstOrLast(com.lealone.db.session.ServerSession, boolean) ,public int[] getColumnIds() ,public int getColumnIndex(com.lealone.db.table.Column) ,public com.lealone.db.table.Column[] getColumns() ,public java.lang.String getCreateSQL() ,public long getDiskSpaceUsed() ,public com.lealone.db.index.IndexColumn[] getIndexColumns() ,public com.lealone.db.index.IndexType getIndexType() ,public long getMemorySpaceUsed() ,public java.lang.String getPlanSQL() ,public com.lealone.db.result.Row getRow(com.lealone.db.session.ServerSession, long) ,public com.lealone.db.table.Table getTable() ,public com.lealone.db.DbObjectType getType() ,public boolean isHidden() ,public boolean isInMemory() ,public boolean isRowIdIndex() ,public boolean needRebuild() ,public void remove(com.lealone.db.session.ServerSession) ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public boolean supportsDistinctQuery() ,public void truncate(com.lealone.db.session.ServerSession) <variables>protected int[] columnIds,protected com.lealone.db.table.Column[] columns,protected com.lealone.db.index.IndexColumn[] indexColumns,protected final non-sealed com.lealone.db.index.IndexType indexType,protected final non-sealed com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/hash/HashIndex.java
|
HashIndex
|
getCost
|
class HashIndex extends IndexBase {
/**
* The index of the indexed column.
*/
protected final int indexColumn;
protected HashIndex(Table table, int id, String indexName, IndexType indexType,
IndexColumn[] columns) {
super(table, id, indexName, indexType, columns);
this.indexColumn = columns[0].column.getColumnId();
}
protected abstract void reset();
protected Value getKey(SearchRow row) {
return row.getValue(indexColumn);
}
protected void checkSearchKey(SearchRow first, SearchRow last) {
if (first == null || last == null) {
throw DbException.getInternalError();
}
if (first != last) {
if (!getKey(first).equals(getKey(last))) {
throw DbException.getInternalError();
}
}
}
@Override
public void truncate(ServerSession session) {
reset();
}
@Override
public long getDiskSpaceUsed() {
return 0;
}
@Override
public void close(ServerSession session) {
// nothing to do
}
@Override
public void remove(ServerSession session) {
// nothing to do
}
@Override
public double getCost(ServerSession session, int[] masks, SortOrder sortOrder) {<FILL_FUNCTION_BODY>}
@Override
public void checkRename() {
// ok
}
@Override
public boolean canGetFirstOrLast() {
return false;
}
@Override
public SearchRow findFirstOrLast(ServerSession session, boolean first) {
throw DbException.getUnsupportedException("HASH");
}
@Override
public boolean canScan() {
return false;
}
@Override
public boolean needRebuild() {
return true;
}
@Override
public boolean isInMemory() {
return true;
}
}
|
if (masks == null) {
return Long.MAX_VALUE;
}
for (Column column : columns) {
int index = column.getColumnId();
int mask = masks[index];
if ((mask & IndexConditionType.EQUALITY) != IndexConditionType.EQUALITY) {
return Long.MAX_VALUE;
}
}
return 2;
| 516
| 104
| 620
|
<methods>public boolean canGetFirstOrLast() ,public boolean canScan() ,public void checkRename() ,public void close(com.lealone.db.session.ServerSession) ,public int compareRows(com.lealone.db.result.SearchRow, com.lealone.db.result.SearchRow) ,public com.lealone.db.index.Cursor find(com.lealone.db.session.ServerSession, CursorParameters<com.lealone.db.result.SearchRow>) ,public com.lealone.db.index.Cursor findDistinct(com.lealone.db.session.ServerSession) ,public com.lealone.db.result.SearchRow findFirstOrLast(com.lealone.db.session.ServerSession, boolean) ,public int[] getColumnIds() ,public int getColumnIndex(com.lealone.db.table.Column) ,public com.lealone.db.table.Column[] getColumns() ,public java.lang.String getCreateSQL() ,public long getDiskSpaceUsed() ,public com.lealone.db.index.IndexColumn[] getIndexColumns() ,public com.lealone.db.index.IndexType getIndexType() ,public long getMemorySpaceUsed() ,public java.lang.String getPlanSQL() ,public com.lealone.db.result.Row getRow(com.lealone.db.session.ServerSession, long) ,public com.lealone.db.table.Table getTable() ,public com.lealone.db.DbObjectType getType() ,public boolean isHidden() ,public boolean isInMemory() ,public boolean isRowIdIndex() ,public boolean needRebuild() ,public void remove(com.lealone.db.session.ServerSession) ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public boolean supportsDistinctQuery() ,public void truncate(com.lealone.db.session.ServerSession) <variables>protected int[] columnIds,protected com.lealone.db.table.Column[] columns,protected com.lealone.db.index.IndexColumn[] indexColumns,protected final non-sealed com.lealone.db.index.IndexType indexType,protected final non-sealed com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/hash/NonUniqueHashIndex.java
|
NonUniqueHashIndex
|
add
|
class NonUniqueHashIndex extends HashIndex {
private final ReadWriteLock lock = new ReentrantReadWriteLock(true);
private ValueHashMap<ArrayList<Long>> rows;
private long rowCount;
public NonUniqueHashIndex(Table table, int id, String indexName, IndexType indexType,
IndexColumn[] columns) {
super(table, id, indexName, indexType, columns);
reset();
}
@Override
protected void reset() {
lock.writeLock().lock();
try {
rows = ValueHashMap.newInstance();
rowCount = 0;
} finally {
lock.writeLock().unlock();
}
}
@Override
public Future<Integer> add(ServerSession session, Row row) {<FILL_FUNCTION_BODY>}
@Override
public Future<Integer> remove(ServerSession session, Row row, boolean isLockedBySelf) {
lock.writeLock().lock();
try {
if (rowCount == 1) {
// last row in table
reset();
} else {
Value key = getKey(row);
ArrayList<Long> positions = rows.get(key);
if (positions.size() == 1) {
// last row with such key
rows.remove(key);
} else {
positions.remove(row.getKey());
}
rowCount--;
}
} finally {
lock.writeLock().unlock();
}
return Future.succeededFuture(Transaction.OPERATION_COMPLETE);
}
@Override
public Cursor find(ServerSession session, SearchRow first, SearchRow last) {
checkSearchKey(first, last);
lock.readLock().lock();
try {
ArrayList<Long> list;
ArrayList<Long> positions = rows.get(getKey(first));
if (positions == null)
list = new ArrayList<>(0);
else
// 这里必须copy一份,执行delete语句时会动态删除,这样会导致执行next()时漏掉一些记录
list = new ArrayList<>(positions);
return new NonUniqueHashCursor(session, table, list);
} finally {
lock.readLock().unlock();
}
}
@Override
public long getRowCount(ServerSession session) {
return rowCount;
}
@Override
public long getRowCountApproximation() {
return rowCount;
}
/**
* Cursor implementation for non-unique hash index
*/
private static class NonUniqueHashCursor implements Cursor {
private final ServerSession session;
private final Table table;
private final ArrayList<Long> positions;
private int index = -1;
public NonUniqueHashCursor(ServerSession session, Table table, ArrayList<Long> positions) {
this.session = session;
this.table = table;
this.positions = positions;
}
@Override
public Row get() {
if (index < 0 || index >= positions.size()) {
return null;
}
return table.getRow(session, positions.get(index));
}
@Override
public boolean next() {
return positions != null && ++index < positions.size();
}
}
}
|
lock.writeLock().lock();
try {
Value key = getKey(row);
ArrayList<Long> positions = rows.get(key);
if (positions == null) {
positions = Utils.newSmallArrayList();
rows.put(key, positions);
}
positions.add(row.getKey());
rowCount++;
} finally {
lock.writeLock().unlock();
}
return Future.succeededFuture(Transaction.OPERATION_COMPLETE);
| 825
| 127
| 952
|
<methods>public boolean canGetFirstOrLast() ,public boolean canScan() ,public void checkRename() ,public void close(com.lealone.db.session.ServerSession) ,public com.lealone.db.result.SearchRow findFirstOrLast(com.lealone.db.session.ServerSession, boolean) ,public double getCost(com.lealone.db.session.ServerSession, int[], com.lealone.db.result.SortOrder) ,public long getDiskSpaceUsed() ,public boolean isInMemory() ,public boolean needRebuild() ,public void remove(com.lealone.db.session.ServerSession) ,public void truncate(com.lealone.db.session.ServerSession) <variables>protected final non-sealed int indexColumn
|
lealone_Lealone
|
Lealone/lealone-db/src/main/java/com/lealone/db/index/hash/UniqueHashIndex.java
|
UniqueHashIndex
|
find
|
class UniqueHashIndex extends HashIndex {
private ConcurrentHashMap<Value, Long> rows;
public UniqueHashIndex(Table table, int id, String indexName, IndexType indexType,
IndexColumn[] columns) {
super(table, id, indexName, indexType, columns);
reset();
}
@Override
protected void reset() {
rows = new ConcurrentHashMap<>();
}
@Override
public Future<Integer> add(ServerSession session, Row row) {
Object old = rows.putIfAbsent(getKey(row), row.getKey());
if (old != null) {
throw getDuplicateKeyException();
}
return Future.succeededFuture(Transaction.OPERATION_COMPLETE);
}
@Override
public Future<Integer> remove(ServerSession session, Row row, boolean isLockedBySelf) {
rows.remove(getKey(row));
return Future.succeededFuture(Transaction.OPERATION_COMPLETE);
}
@Override
public Cursor find(ServerSession session, SearchRow first, SearchRow last) {<FILL_FUNCTION_BODY>}
@Override
public long getRowCount(ServerSession session) {
return getRowCountApproximation();
}
@Override
public long getRowCountApproximation() {
return rows.size();
}
/**
* A cursor with at most one row.
*/
private static class SingleRowCursor implements Cursor {
private Row row;
private boolean end;
/**
* Create a new cursor.
*
* @param row - the single row (if null then cursor is empty)
*/
public SingleRowCursor(Row row) {
this.row = row;
}
@Override
public Row get() {
return row;
}
@Override
public boolean next() {
if (row == null || end) {
row = null;
return false;
}
end = true;
return true;
}
}
}
|
checkSearchKey(first, last);
Row result;
Long pos = rows.get(getKey(first));
if (pos == null) {
result = null;
} else {
result = table.getRow(session, pos.intValue());
}
return new SingleRowCursor(result);
| 532
| 81
| 613
|
<methods>public boolean canGetFirstOrLast() ,public boolean canScan() ,public void checkRename() ,public void close(com.lealone.db.session.ServerSession) ,public com.lealone.db.result.SearchRow findFirstOrLast(com.lealone.db.session.ServerSession, boolean) ,public double getCost(com.lealone.db.session.ServerSession, int[], com.lealone.db.result.SortOrder) ,public long getDiskSpaceUsed() ,public boolean isInMemory() ,public boolean needRebuild() ,public void remove(com.lealone.db.session.ServerSession) ,public void truncate(com.lealone.db.session.ServerSession) <variables>protected final non-sealed int indexColumn
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.