⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 apimanager.java

📁 一个简单的数据库
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package apiManager;import java.io.FileNotFoundException;import java.util.*;import database.*;import fileManager.*;import catalogManager.*;import bufferedManager.*;import indexManager.*;import java.io.File;import java.io.FileInputStream;import java.io.ObjectInputStream;/** * * @author outlaw */public class APIManager {    public static void createDataBase(String path,String name) throws Exception{        DataBaseData newDB=new DataBaseData(path,name,new Date());//创建时写回去        FileManager.writeOutObject(newDB,newDB.getPath()+newDB.getName()+".db");        CatalogManager.addDB(newDB.getName());        CatalogManager.setCurDB(newDB);        throw new Success("Creating Database["+name+"] succeeded!");    }    public static void createTable(String tbName,ArrayList<String> attrName,ArrayList<String> type,ArrayList<Integer> feature) throws Exception{        String path=CatalogManager.getCurDB().getPath()+"tables/";        DataBaseData db1=CatalogManager.getCurDB();        TableData newTB=new TableData(db1.getDBID(),db1.getTBNumber(),path,tbName,new Date());        int len=attrName.size();        int keyIndex=-1;        ArrayList<Integer> key_id=new ArrayList<Integer>();        for(int i=0;i<len;i++){            Attribute newAttri=new Attribute((String)attrName.get(i),(String)type.get(i),newTB.getName());            switch((Integer)feature.get(i))            {                case 2:                 {                       newAttri.setIsUnique(true);                    newAttri.setIsKey(true);                    keyIndex=i;                    key_id.add(i);                }break;                 case 1:                 {                    newAttri.setIsUnique(true);                    key_id.add(i);                }break;            }            newTB.addAttri(newAttri);        }        CatalogManager.getCurDB().addTable(newTB);        //FileManager.writeOutObj8ect(newTB, path+tbName+".tbl");        DataBaseData db2= CatalogManager.getCurDB();        FileManager.writeOutObject(db2,db2.getPath()+db2.getName()+".db");        FileManager.createFile(path+tbName+".tbl");        FileManager.makeDir(path+tbName+"_index/");                for(int i=0;i<key_id.size();i++)        {            createKeyIndex(newTB,key_id.get(i));        }         //if(keyIndex!=-1)           //createKeyIndex(newTB,keyIndex);        throw new Success("Creating table["+tbName+"] succeeded!");    }    public static void createKeyIndex(TableData tb,int keyIndex) throws Exception    {        //params里面依次存放的是:index name,table name,attribute name        String[] params=new String[3];        String keyName=tb.getAttribName(keyIndex);        //params[0]="keyIndex";        params[0]=keyName+"_auto_index";        params[1]=tb.getName();        params[2]=keyName;        createIndex(params,false);    }    public static void testConflict(String[] values,TableData tb) throws Exception    {        ArrayList<Index> indices=IndexManager.indices;        int len=indices.size();        for(int i=0;i<len;i++)        {            Index index=indices.get(i);            if(index.getTBName().equals(tb.getName()))            {                int id=tb.getAttribIDByName(index.getAttribName());                String value=values[id];                String type=tb.getAttribType(id);                Comparable key=getKeyForIndex(value,type);                if(!index.isEmpty())                {                    Bucket bucket=index.find(key);                    if(bucket!=null)                        throw new OperationInfo("Insert error!You have inserted two identical values:" +                                value+"of attribute["+index.getAttribName()+"]");                }            }        }        for(int i=0;i<tb.getIndices().size();i++)        {            IndexTag tag=tb.getIndices().get(i);            if(tag.isInFile())            {                Index index=IndexManager.readIndexIntoMemory(tag.getFullName());                tag.setNotInFile();                int id=tb.getAttribIDByName(index.getAttribName());                String value=values[id];                String type=tb.getAttribType(id);                Comparable key=getKeyForIndex(value,type);                if(!index.isEmpty())                {                    Bucket bucket=index.find(key);                    if(bucket!=null)                        throw new OperationInfo("Insert error!You have inserted two identical values:" +                                value+"of attribute["+index.getAttribName()+"]");                }            }        }    }        public static void insertTuple(String[] values,String tbName) throws Exception    {        Tuple tuple=new Tuple(values);        TableData tb=CatalogManager.getTableByName(tbName);        Block existBlock=BufferedManager.getBlock(tb);        testConflict(values,tb);        if(existBlock!=null)        {            int tupleID=existBlock.addTuple(tuple);            existBlock.setDirty();            insertIntoIndex(tb,existBlock.getBlockID(),tupleID,values);            tb.incTupleNumber();            throw new Success("Insert tuple successed!");        }        else        {            Block block=new Block(tb.getName(),tb.getBlockNumber(),tb.getTupleSizeInBlock());            tb.addBlockLogical();            int tupleID=block.addTuple(tuple);                      BufferedManager.addBlock(block);              insertIntoIndex(tb,block.getBlockID(),tupleID,values);            tb.incTupleNumber();            throw new Success("Insert tuple successed!");        }        //FileManager.writeBlockBack(block);    }    public static void quit() throws Exception    {       throw new Quit();    }    public static void createIndex(String[] params,boolean is_throw) throws Exception    {        //params里面依次存放的是:index name,table name,attribute name        String indName=params[0];        String tbName=params[1];        String attribName=params[2];         TableData tb=CatalogManager.getTableByName(tbName);        IndexTag indTag=new IndexTag(tb,indName,attribName);        tb.addIndexTag(indTag);                Index index=new Index(tbName,tb.getPath(),indName,attribName);        IndexManager.addIndex(index);        addRecordsToIndex(tb,index);        FileManager.writeOutIndex(index);        if(is_throw)            throw new Success("Creating index["+indName+"] succeeded!");    }    public static void addRecordsToIndex(TableData tb,Index index) throws Exception    {        Block block=null;        ArrayList<Block> blocks=BufferedManager.blocks;        int len=blocks.size();        int attribID=tb.getAttribIDByName(index.getAttribName());        String type=tb.getAttribType(attribID);                for(int i=0;i<len;i++)        {            block=blocks.get(i);            if(block.getTBName().equals(tb.getName()))            {                Tuple[] tuples=block.getTuples();                int[] Notavailable=block.getNotAvailablePos();                for(int j=0;j<Notavailable.length;j++)                {                    Comparable key=tuples[Notavailable[j]].getValue(attribID, type);                                       Bucket bucket=new Bucket(key,block.getBlockID(),Notavailable[j]);                    index.insert(bucket);                    //Bucket bucket2=index.find(key);                    //System.out.println(bucket2.toString());                }            }        }                for(int i=0;i<tb.getBlockNumber();i++)        {            if(tb.isBlockInFile(i))            {                block=BufferedManager.putBlockIntoMemory(tb,i);                Tuple[] tuples=block.getTuples();                int[] Notavailable=block.getNotAvailablePos();                for(int j=0;j<Notavailable.length;j++)                {                    Comparable key=tuples[Notavailable[j]].getValue(attribID, type);                    Bucket bucket=new Bucket(key,block.getBlockID(),Notavailable[j]);                    index.insert(bucket);                    Bucket bucket2=index.find(key);                    //System.out.println(bucket2.toString());                }            }        }    }    public static void dropTable(String tbName) throws Exception    {              TableData tb=CatalogManager.getTableByName(tbName);                deleteOnCasecade(tb.getFullNameWithSuffix());                removeBlockFromMemory(tbName);        removeIndexFromMemory(tbName);        removeIndexFromDisk(tbName);        removeFromDB(tbName);        throw new Success("Drop table:["+tbName+"] successed!");    }    public static void removeFromDB(String tbName)    {        DataBaseData db=CatalogManager.getCurDB();        ArrayList<TableData> tables=db.getTables();        int len=tables.size();        //这是一个经典错误;        /*for(int i=0;i<len;i++)        {            if(tables.get(i).getName().equals(tbName))                tables.remove(i);        }*/        for(int i=0;i<len;i++)        {            if(tables.get(i).getName().equals(tbName))            {                tables.remove(i);                break;            }        }    }    public static void removeIndexFromMemory(String tbName)    {        //必须把这个table所有的index从内存中搞掉,不然关掉程序的时候        //又会把index写到磁盘上去。        ArrayList<Index> indices=IndexManager.getIndices();        for(int i=0;i<indices.size();i++)        {            if(indices.get(i).getTBName().equals(tbName))            {                indices.remove(i);                i--;            }        }    }    public static void removeIndexFromDisk(String tbName) throws Exception    {        TableData tb=CatalogManager.getTableByName(tbName);        String indexFullName=tb.getFullName()+"_index/";        File indexFile=new File(indexFullName);        if(indexFile.exists())        {            deleteOnCasecade(indexFile);        }    }    public static void deleteOnCasecade(File file) throws Exception    {        //System.out.println(file.getAbsoluteFile());        if(!file.isDirectory())        {            file.delete();        }        else        {            String[] files=file.list();            int len=files.length;            for(int i=0;i<len;i++)            {                File deleteFile=new File(file.getAbsolutePath()+"/"+files[i]);                if(deleteFile.exists())                    deleteFile.delete();            }            file.delete();        }    }    public static void deleteOnCasecade(String fullName) throws Exception    {        File file=new File(fullName);        deleteOnCasecade(file);    }    public static void dropIndex(String indName,TableData tb) throws Exception    {        IndexTag tag=tb.getIndexTagByIndexName(indName);        if(tag==null)            throw new OperationInfo("The index ["+indName+"]has doesn't exist!");        deleteIndexFromDisk(tag.getFullName());        deleteIndexFromMemory(indName,tb.getName());        tb.removeIndexTagByIndexName(indName);        throw new Success("Drop index "+indName+" on "+tb.getName()+" succeeded!");    }    private static void deleteIndexFromDisk(String fullName) throws Exception    {        deleteOnCasecade(fullName);    }    private static void deleteIndexFromMemory(String indName,String tbName) throws Exception    {        ArrayList<Index> indices=IndexManager.getIndices();                for(int i=0;i<indices.size();i++)        {            Index index=indices.get(i);            if(index.getTBName().equals(tbName)&&index.getIndexName().equals(indName))            {                indices.remove(i);                i--;            }        }    }    public static void open() throws Exception    {        CatalogManager.initDBInfo();        IndexManager.open();    }    public static void close(String log) throws Exception    {        FileManager.writeOutDataBaseInfo();        closeIndex();        FileManager.writeOutDataBase();        //FileManager.writeOutTables();        BufferedManager.writeBlocksBack();        IndexManager.close();        writeOutLog(log);    }    public static void writeOutLog(String log) throws Exception    {        FileManager.writeOutLog(log);    }    public static void closeIndex()    {        ArrayList<TableData> tables=CatalogManager.getCurDB().getTables();        int len=tables.size();

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -