Giter Club home page Giter Club logo

sorm's Introduction

SORM GitHub version build license

Simple and stupid ORM for Android

setup

add this project as you Android project library

Usage

Create a table

the model

@Table  
public class User extends Model {  

	@Column  
	@Index //index support
	private long userid; 

	@Column   
	private int age;  

	@Column  
	private String name;  

	public long getUserid() {
		return userid;
	}

	public void setUserid(long userid) {
		this.userid = userid;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

update & automantily insert if not exist

	Admin a1 = new Admin();  
	a1.setAdminName("a111");  
	a1.setId(1);  
	a1.save(getContext());  
	//or you can save in async way
	a1.saveAsync(getContext(),  new ORMcallback() {

				@Override
				public void onFinish() {
					
				}

				@Override
				public void onFaild() {
					
				}
			});

query

	List<Admin> admins = new Query(new Selector().from(Admin.class))
				.excute(getContext());  
	// or query  in async way
	Selector selector = new Selector().from(Admin.class);
	new Query(selector).excuteAsync(getContext(), new QueryCallback() {

			@Override
			public void onFinish(Object result) {
				List<Admin> res = (List<Admin>) result;
			}
		});

delete

	List<Admin> admins = new Query(new Selector().from(Admin.class))
				.excute(getContext());  
	for(Admin a: admins){  
		a.delete(getContext());  
		//or you can save in async way
		a.deleteAsync(getContext(),  new ORMcallback() {

				@Override
				public void onFinish() {
				
				}

				@Override
				public void onFaild() {
				
				}
			});
	}  

Five Operation

  • build entity
	new Creater().from(User.class).build()
  • insert
  
    User u = new User();    
    u.setAge(11);     
    u.setName("aaa");     
    String sql = new Inserter().insert(u ).build();    
  • delete
	String sql = new Deletor()
				.from(User.class)
				.where("id", "=", "1")
				.and().where("age", ">", "18")
				.build();
  • select
	String sql = new Selector("id","title","content") //the result columns. select all(*) when nothing here
					.from(Database.class)  //table
					.distinct() // all() or distinct()
					.where("showFlag","=", 1 + "")   //`where` expression
					.and().where("version", "!=", "0")
					.groupBy("id","title")  //more than one
					.orderBy("id") //ablt to more than one
					.limit(10)
					.offset(10)
					.build();
  • update
	User u = new User();
	u.setAge(11);
	u.setName("bbb");
	u.setSaveTime(12354546);
	u.setId(1);
	String sql = new Updater()
					.update(u)
					.where("id", "=", "1")
					.build();

advance

  • drop table & index
//drop table  
String sql = new Droper().Table().from(Animal.class).build();  
//drop index  
String sql = new Droper().Index().from(Animal.class).build();  
//invoke  sql  
DBUtils.execSQL(context,sql);

//why not do this:  
new Droper().Index().from(cls).excute(getContext());  
new Droper().Table().from(cls).excute(getContext());  

sorm's People

Contributors

jayin avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

boy1583

sorm's Issues

delete的逻辑

一般情况下:
要删除元素,该元素一般是从数据库中取出,然后进行删除

但是用户可能曲解删除的意思(or 不小心这么写了):
没有先取出来,而是自己构造直接删除,这样就会出错了

数据库泄露

see:

06-08 05:36:29.440: W/SQLiteConnectionPool(5400): A SQLiteConnection object for database '/data/data/io.github.jayin.test/databases/mydb.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

06-08 05:36:29.440: W/SQLiteConnectionPool(5400): A SQLiteConnection object for database '/data/data/io.github.jayin.test/databases/mydb.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

where语句对于条件是String 失效

Delete From User Where id = 1 and name != Jason 

should be:

Delete From User Where id = 1 and name != "Jason" 

more easy:

Delete From User Where id = "1" and name != "Jason" 

sqlite数据库会自动帮你转

支持多层次继承

目前仅支持一层:

User extends Model

需求有可能是:

BasicEntity extends Model;

User extends BasicEntity;

Admin extends BasicEntity;

each table has only one Primary Key

bug like:

class Student extends Human {
    @PrimaryKey
    long id;

    int age;

    String name;

    List<Integer> friendid;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Integer> getFriendid() {
        return friendid;
    }

    public void setFriendid(List<Integer> friendid) {
        this.friendid = friendid;
    }

}

class Human extends Model {

    int height;

    int wight;

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWight() {
        return wight;
    }

    public void setWight(int wight) {
        this.wight = wight;
    }

}

the sql below is incorrect

Create Table Student (name TEXT ,id INTEGER Primary Key AUTOINCREMENT,age INTEGER ,height INTEGER ,wight INTEGER ,__id INTEGER Primary Key AUTOINCREMENT)

typically,we are support to follow the user ---- remove the __id

SQL Injection

discusses with @fritx at dade3bb


insert

Student s = new Student();
        s.setName("jayin\" or 1=\"1");
        s.save(getContext());

output

Insert Into Student (name) Values ("jayin" or 1="1") 

Delete

String sql = new Deletor().from(Student.class)
                .where("name", "=", "jayin\" or 1=\"1").build();

output

Delete From Student Where name = "jayin" or 1="1" 

select

String sql = new Selector().from(Student.class).where("name", "=", injection).build();

output

Select All * From Student Where name = "jayin" or 1="1"  

update

String sql = new Updater().update(s).where("name", "=", injection).build();

output

Update Student Set name="jayin" or 1="1" Where name = "jayin" or 1="1" 

should be:

Delete From Student Where name = "jayin\" or 1=\"1" 

Select All * From Student Where name = "jayin\" or 1=\"1"  

Update Student Set name="jayin" or 1="1" Where name = "jayin\" or 1=\"1" 

SQLite有个特点,就是删除了数据,文件容量不会减少,要自行操作减少

参考:http://www.sqlite.org/lang_vacuum.html

    /**
     * 压缩数据库
     * 如果删除了大量数据,而又想缩小数据库文件占用的空间,执行 VACUUM 命令。 VACUUM      
     * 将会从头重新组织数据库。这将会使用数据库有一个空的“自由链表”, 数据库文件也会最小。但要注意的是, VACUUM      
     * 的执行会需要一些时间 (在SQLite开发时,在Linux上,大约每M字节需要半秒种),并且,      
     * 执行过程中需要原数据库文件至多两倍的临时磁盘空间。 
     * @throws DbException 抛出异常
     */
    public void CompressDb() throws DbException {
        execNonQuery("VACUUM");
    }

Model.save

设计思路:
每个实体类都是一个Model(e.g. User extends Model)
如果在保存or更新一条记录的时候,显然这样做的最人性化的:

user.save()

但是弊端就是要连接数据,的给个上下文才能获得db object.那么解决办法有3种
1

user.init(context).save()    

//这样虽然可以接受,但是每次插入的时候添加init(context),感觉有些少冗余?容易忘了init?

在Application里面:

DB.init(context)

那么在可以

user.save()
//在save函数里面通过静态方法的db object.获取即可

//这种也是不失为一种好解决办法,一次初始化,到处爽!但是如果换了别人来维护,很可能忘记在application里面初始化,或者从内存的角度来看,整个application均持有db object,这样浪费内存。

3
这是一种折中的办法

user.save(context)

没有一次初始化到处使用,也没有init(context) 那么冗余的感觉

这里我尝试采用第三种方法去实现。

save()的实现要点

1 同内建一个__id,来表示每一条记录
2 save()可以是插入or更新,这就是通过__id的存在性来判断了

Query

API:
查询不应该放在Modle!

new Query(selector).excute(context)
//expression = new selector().from()........build()

return List

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.