HomeJavaModsSQLibrary-BungeeCord
SQLibrary-BungeeCord
ModsJava

SQLibrary-BungeeCord

A Powerful Database Modeling and Connection Handling SQL Library. Free Minecraft Java mod — download and open it in the game.

⬇ Download on Spigot
SQLibrary for Bungee- Database Development Made Easy
Version: 1.1.0-SNAPSHOT

SQLibrary is Powerful Utility for establishing SQL Database Connections and Creating Powerful Database Models Similar to Laravel's Eloquent Database Modeling Library for PHP.

Disclaimer: This plugin is a utility designed for Developers to assist in developing plugins using SQL Databases and only serves as a requirement for those plugins to work.

Features:
- An Easy Method of Establishing MySQL and SQLite Connections including an API to support any SQL server.

- A Powerful Database Factory / Model Building Library allowing a developer to add SQL support to any application without needing to know any SQL syntax.

- Individual SQL Server wrapping profiles designed to automatically escape, wrap and build SQL statements and prevent SQL injection.

- Code Based Condition Building Library for use with building Models.

- FieldFormat Library to automatically parse database fields when loaded to and from Database Models.

Alternate SQLibrary Downloads:
SQLibrary Standalone: Download
SQLibrary for Spigot: Download

Adding SQLibrary to your Project:
Include the Following in your plugin.yml and you're ready to go.
Code (Text):
softdepend: [SQLibrary-BungeeCord]
Example Project:
As the documentation for SQLibrary has not yet been written I have created an example project would should demonstrate the usage of SQLibrary. I will be developing a model capable of storing player group and balance information.

I will be using the following fields:
- player_id (Primary Key)
- player_uuid (Player UUID)
- group (Player Group VARCHAR)
- balance (Player Balance DOUBLE)

Firstly to create model capable of building and interacting with a database using the fields above I need 3 things:
- A DatabaseConnection either MySQLConnection or SQLiteConnection
- A DatabaseModel containing all the specified fields. Each initialized object of this model will represent 1 row / entity in the database.
- A ModelFactory designed to perform queries and interact with the database based on the provided model.

The Steps are as Follows:
- Step 1: Create a Database Connection
- Step 2: Create the Player Model
- Step 3: Create The Player ModelFactory

Once these steps are all completed we can move onto some examples.

Step 1: Creating a DatabaseConnection.

SQLibrary currently supports 2 forms of SQL Server Support. MySQL and SQLite. It is up to you as a Developer to decide which your plugin will support or both! Remember you will need to setup an additional set of models and factories in your project to support the different Database Requirements.

Code (Text):
public static void startDatabaseConnection() {

        //Creating a MySQLConnection
        DatabaseConnection connection = new MySQLConnection(host, port, database, user, pass);

        //Creating a SQLiteConnection
        DatabaseConnection  connection = new SQLiteConnection(new File("my.db");

        //Opening a DatabaseConnection
        connection.openConnection();


}

Step 2: Create the Player Model.
Now we have setup our DatabaseConnection we now need to develop our player Model. As stated above the PlayerModel when initialized represents 1 entry in a given SQL Database. You will be required to make at least 1 model for each table in your Database.

To do this you will need to setup fields in your model to match each field in your database by using the attribute @Fillable. SQLibrary can also automatically build your tables for you by using an optional @Schema attribute for this example we will be using both.


Code (Text):
import java.util.UUID;

import code.nextgen.sqlibrary.database.utils.Result;
import code.nextgen.sqlibrary.model.Model;
import code.nextgen.sqlibrary.model.ModelFactory;
import code.nextgen.sqlibrary.model.annotation.Fillable;
import code.nextgen.sqlibrary.model.annotation.PrimaryKey;
import code.nextgen.sqlibrary.model.annotation.Schema;
import code.nextgen.sqlibrary.model.annotation.UniqueKey;
import code.nextgen.sqlibrary.model.common.UUIDFormat;

public class PlayerModel extends Model {

    @PrimaryKey(name = "pk_player") //Add Primary Key Constraint with name "pk_player"
    @Fillable(column = "player_id", sortingIndex = 1)  //Specify Column Name and Sorting Index
    @Schema(attributes = "INT NOT NULL AUTO_INCREMENT") //Specify Schema Attributes
    public Integer playerID;

    @UniqueKey(name = "uk_player_uuid") //Add a Unique Key constraint
    @Fillable(column = "player_uuid", sortingIndex = 2, formatField = UUIDFormat.class) //Specify a Field format to Automatically parse between UUID and VARCHAR types
    @Schema(attributes = "VARCHAR(50) NOT NULL")
    public UUID playerUUID;

    @Fillable(column = "group", sortingIndex = 3)
    @Schema(attributes = "VARCHAR(255)")
    public String playerGroup;

    @Fillable(column = "balance", sortingIndex = 4)
    @Schema(attributes = "DOUBLE NOT NULL DEFAULT '0.0'")
    public double balance;

    public PlayerModel(ModelFactory<Model> model, Result result) throws IllegalArgumentException,
            IllegalAccessException, InstantiationException {
 
        super(model, result);
    }

}
 
Available Attributes:
@Fillable(column = "", sortingIndex = 1, formatField = <? extends FieldFormat>.class)
Specifys a fillable database field to be initialized when a model is created. Column specifys the name of the column, sortingIndex should be specified in order of fields defined as this information can't be collected at runtime. FieldFormat is an optional attribute that can be used to assign a FieldFormat class in charge of parsing values to and from the database.

@Schema(attributes = "")
Used to specify Schema Attributes to be used when building tables

@PrimaryKey(String name = "", schema = true)
Used to automatically assign id's to inserted models and provides. Setting schema to true (default) will create a Primary Key constraint when building tables.

@UniqueKey(String name = "", references = String...)
Used to create a Unique constraint when building tables.

@ForeignKey(String name = "", table = "", key = "")
Used to create a ForeignKey Constraint when building tables.


Step 3: Create The Player ModelFactory

A ModelFactory is a single instance that contains all the available functions for creating, inserting, updating and deleting database entres a specified model. This is also encharge of building tables. But don't worry all these functions already exist. Setting up a factory is like filling in a form, although feel free to customize your factory and create your own functions.

Code (Text):
import java.util.logging.Level;

import org.bukkit.Bukkit;

import code.nextgen.sqlibrary.database.DatabaseConnection;
import code.nextgen.sqlibrary.model.ModelFactory;

public class PlayerFactory extends ModelFactory<PlayerModel> {

    private static PlayerFactory INSTANCE;

    private final DatabaseConnection connection;

    public PlayerFactory(DatabaseConnection connection) {
        super(PlayerModel.class); //This is required as Generic Types cannot be obtained at runtime
        this.connection = connection;
        PlayerFactory.INSTANCE = this;
    }

    @Override
    public String getTable() {
        return "players"; //The Name of the Table this ModelFactory will be using
    }

    @Override
    public DatabaseConnection getDatabase() {
        return connection; //The DatabaseConnection you wish to use
    }

    //Where Errors will be Logged. If an error occurs SQLibrary will return either null or false
    @Override
    public void log(Level level, String message, Throwable thrown) {
        Bukkit.getLogger().log(level, message, thrown);
    }

    //Get our PlayerFactory Instance
    public static PlayerFactory getInstance() {
        return INSTANCE;
    }
}
 
Initializing the PlayerFactory
Code (Text):
    new PlayerFactory(connection)

Now our project is all setup we can now start working with some examples:

Building Tables:
Code (Text):

    //Building Database Schema
    PlayerFactory.getInstance().buildSchema();
 
Inserting a Model:
Code (Text):

    //Inserting a new PlayerModel
    Player tom = Bukkit.getPlayer("tom"); //Use ProxiedPlayer for BungeeCord

    //Create a Blank Player Model for Insertion
    PlayerModel tomModel = PlayerFactory.getInstance().prepareBlankModel();
    tomModel.playerUUID = tom.getUniqueId();
    tomModel.playerGroup = "Admin";
    tomModel.balance = 199.99;

    //Insert Model
    if(!PlayerFactory.getInstance().insert(tomModel)) {
        //Insertion Failed
        return;
 
    }
    //Model Inserted

 

Selecting Models:

Code (Text):

    Player tom = Bukkit.getPlayer("tom");

    //Create a Search Condition
    Condition condition = Condition.fieldEquals("player_uuid", tom.getUniqueId(),
            PlayerFactory.getInstance().getProfile()); //Get Current SQLWrapping Profile (NOT REQUIRED BUT RECOMMENDED)

    //Get a list of models matching specified Condition
    List<PlayerModel> models = PlayerFactory.getInstance().select(condition);

    if(models == null) {
        //ERROR
        return;
    }

    if(models.size() < 1) {
        //No Entries matching query
        return;
    }

    PlayerModel tomModel = models.get(0);
 
Updating a Model:
Code (Text):


        //Update Model
        tomModel.balance += 300; //Add 300 to balance
        if(!PlayerFactory.getInstance().update(tomModel, "balance")) { //Update Database
            //Update Failed
            return;
        }
        //Updated
 
 
Deleting a Model:
Code (Text):

    //Delete Model
    if(!PlayerFactory.getInstance().delete(tomModel)) {
        //Deletion Failed
        return;
    }
    //Deleted
 
Copyright
© Cody Rees-Whitley 2016

SQLibrary-BungeeCord is a free Minecraft Java mod. Downloaded 2,160 times (via Spigot). Download it and open it directly in the game.

Explore more