{"id":18820682,"url":"https://github.com/valentinfunk/libk","last_synced_at":"2025-04-13T23:34:17.064Z","repository":{"id":12833178,"uuid":"15508587","full_name":"ValentinFunk/LibK","owner":"ValentinFunk","description":"Library for fast gmod addon development","archived":false,"fork":false,"pushed_at":"2023-12-04T12:02:22.000Z","size":3296,"stargazers_count":53,"open_issues_count":6,"forks_count":21,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-03-27T14:08:17.038Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Lua","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ValentinFunk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-12-29T13:06:24.000Z","updated_at":"2024-10-15T19:58:54.000Z","dependencies_parsed_at":"2024-11-08T00:30:07.619Z","dependency_job_id":"e9d8e3da-6877-4d88-bcd2-7bd34fc2b120","html_url":"https://github.com/ValentinFunk/LibK","commit_stats":null,"previous_names":["valentinfunk/libk"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValentinFunk%2FLibK","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValentinFunk%2FLibK/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValentinFunk%2FLibK/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValentinFunk%2FLibK/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ValentinFunk","download_url":"https://codeload.github.com/ValentinFunk/LibK/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248797949,"owners_count":21163215,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-08T00:29:29.917Z","updated_at":"2025-04-13T23:34:17.052Z","avatar_url":"https://github.com/ValentinFunk.png","language":"Lua","funding_links":[],"categories":[],"sub_categories":[],"readme":"LibK\n====\n\nGMOD Lua Library for fast and simple development of database backed addons. Support MySQL and SQLite with the same code.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/Kamshak/LibK/blob/master/logo.png?raw=true\" alt=\"LibK Banner\"/\u003e\n\u003c/p\u003e\n\n## Database\nLibK provides a few tools for database interaction:\n- Abstraction through models with support for SQLite and MySQL: **No mode manual query writing - No more SQL injection**\n- Possibility to set up a database connection very easily\n- Gurantee that every query will be executed, automatic reconnection on database connection interruption\n\n## Networking\n- Clients can start server transactions that are wrapped as a promise\n- Objects (i.e. class instances) can be sent from server to client\n\n## Addon Loader\n- Easy loading by filename\n- Supports file ordering\n- No need to manually include files anymore\n- Load an addon after gamemode intialization\n- Wait until another addon has finished loading\n\n\n## Basics\nThis example shows a simple addon that will save player joins to the database. In any shared file: \n```lua\n-- Initialize the Addon\nLibK.InitializeAddon{\n\taddonName = \"MyAddon\",                  --Name of the addon\n\tauthor = \"Kamshak\",                     --Name of the author\n\tluaroot = \"myaddon\",                    --Folder that contains the client/shared/server structure\n}\n\nMyAddon = {}\n\nLibK.SetupDatabase( \"MyAddon\", MyAddon )\n\n-- Create a Database Model\nMyAddon.PlayerJoins = class( \"PlayerJoins\" )\nMyAddon.PlayerJoins.static.DB = \"MyAddon\"\nMyAddon.PlayerJoins.static.model = {\n\ttableName = \"ps2_plyjoinstreak\",\n\tfields = {\n\t\tplayerId = \"int\",\n        \tjoinedTime = \"createdTime\" --automatically set to time this entry was created\n\t}\n}\nMyAddon.PlayerJoins:include( DatabaseModel )\n\n-- Use It\nhook.Add( \"LibK_PlayerInitialSpawn\", \"Save Player Join\", function( ply )\n\tlocal join = Pointshop2.PlayerJoins:new( )\n\tjoin.playerId = ply.kPlayerId\n\tjoin:save()\nend )\n\n```\n\n## Addon Structure\nLibK suggests a simple addon structure that seperates code and divides code into shared, server and client folders.\n- addons\n  - LibK\n  - YourAddon\n    - lua\n      - autorun\n        - youraddon_init.lua \n      - youraddon\n        - client\n        - shared\n          - sh\\_0\\_youraddon.lua\n          - sh_config.lua\n        - server\n          - sv_youraddon.lua \n\nThis is purely optional, some features can only be used with this structure however.\n\n## Setting up an addon\nThe file youraddon_init.lua should call LibK.InitializeAddon which automatically adds client and shared files to the lua datapack and the addon reload list. The reload list allows you to fully reload your addon using a console command. It makes sure that all dependent addons are loaded in the correct order.\n\nShared code is always loaded before server/client specific code.\nTo further specify load orders use numbers in the file names, e.g.:\n\n- sh\\_0\\_loadedFirst.lua\n- sh\\_1\\_loadedSecond.lua\n- sh_doesntMatterWhenLoaded.lua\n\nExample file content:\n\nyouraddon_init.lua:\n```lua\n--Example:\nLibK.InitializeAddon{\n\taddonName = \"YourAddon\",                  --Name of the addon\n\tauthor = \"Kamshak\",                       --Name of the author\n\tluaroot = \"youraddon\",                    --Folder that contains the client/shared/server structure relative to the                                               --lua folder\n}\nLibK.addReloadFile( \"autorun/youraddon_init.lua\" ) --Path to the file so it can be reloaded using the libk_reload command\n```\n\nsh\\_0\\_youraddon.lua:\n```lua\nYourAddon = {}\n```\nThe global addon table is created shared.\n\n\nsh_config.lua:\n```lua\nYourAddon.Config = {}\nYourAddon.Config.startHp = 100 --Example setting\n```\nAll settings should be put in here. Everything should be commented.\n\n\nsv_youraddon.lua:\n```lua\nLibK.SetupDatabase( \"YourAddon\", YourAddon )\n```\nThe database connection is set up(see below for details)\n\n\n### Setting up a database connection\nGenerally every addon using LibK should have a global addon table that contains all models.\n\nTo get a database connection the function LibK.SetupDatabase( pluginName, pluginTable ) should be used. pluginName a string used to identify the addon and a unique identifier. pluginTable is the global addon table that contains all models. \n\n```lua\n--Example:\nLibK.SetupDatabase( \"YourAddon\", YourAddon )\n```\n\nThe database will connect using the LibK settings (MySQL or SQLite) and initialize all models (create tables etc.)\nWhen the datbase has connected the function YourAddon.onDatabaseConnected will be called if it exists.\n\n### Models\nThe main feature of LibK are models, these allow backend independent usage of databases.\nThe plugin generally follows the cakephp conventions.\n\nA model needs to be a class that has a static DB string, which is the identifier given to LibK.SetupDatabase.\nIt then needs a static model table which contains info about the fields. The format is a table with field name as the keys and field type as values. An id field is automatically added to each table and does not have to be specified\n\nAvailable fieldtypes are:\n- string:\n  Maximum 255 Characters long string\n- int:\n  Integer value, cannot be NULL\n- optKey:\n  Optional key to a different table, can be NULL\n- table:\n  Special field, if this is set the object's first level table is serialized and saved to the database, else only \n  class.saveFields fields are saved. This should not be used much but can be useful sometimes when the structure of an object can differ\n- bool:\n  True or False (0 or 1)\n- player:\n  Datatype to save a player reference by SteamID, difference to string is that some more magic functions work with it.\n- playerUid:\n  Int big enough to save a player's unique id\n- classname:\n  Special field, automatically saves the classname of the class. If you want to save inherited classes this can be useful\n- createdTime:\n  Automatically set to the time the entry was created (timestamp)\n- updatedTime:\n  Automatically set to the time the entry was last updated (timestamp)\n- time:\n  Time field (timestamp)\n- text:\n  Long chunk of text(=MEDIUMTEXT)\n\nTime fields are saved as TIMESTAMP and automatically converted to a number in lua when the object is loaded.\n\nExample model:\n```lua\nKMapVote.Rating = class( \"KRating\" )\n\nKMapVote.Rating.static.DB = \"KMapVote\" --The identifier of the database as given to LibK.SetupDatabase\nKMapVote.Rating.static.model = {\n\ttableName = \"kmapvote_ratings\",\n\tfields = {\n\t\townerId = \"int\",\n\t\tstars = \"int\",\n\t\tcomment = \"text\", \n\t\tmapname = \"string\"\n  }\n}\n\nKMapVote.Rating:include( DatabaseModel ) --Adds the model functionality and automagic functions\n```\nThe global plugin table is KMapVote in this case. \n\nTo load objects you can use the created automagic functions model.findByField( value ).\nYou can also specify a custom WHERE query using model.getDbEntries( whereString ).\nThese functions return a promise that returns the found objects.\nExamples:\n```lua\n--Find all ratings owned by player with id 5\nKMapVote.Rating.findByOwnerId( 5 )\n:Then( function( ratings )\n    for _, rating in pairs( ratings ) do\n      print( \"Map Rating for map \" .. rating.mapname .. \":\" )\n      print( \"-\u003e \" .. rating.stars .. \" stars\" )\n    end\nend )\n\n--Get all ratings:\nKMapVote.Rating.getDbEntries( \"WHERE 1 = 1\" )\n:Then( function( allRatings )\n    PrintTable( allRatings )\nend )\n```\n\nTo create a new db entry use model:new( ) \nthen model:save( ) to save it\n```lua\nlocal rating = KMapVote.Rating:new( )\nrating.stars = 4\nrating.ownerId = player.GetByID( 2 ).kPlayerId\nrating.mapname = game.GetMap( )\nrating:save( )\n:Done( function( )\n  print( \"Saved the rating!\" )\nend )\n:Fail( function( errid, err )\n  print( \"Couldn't save the rating :( errror was: \", err )\nend )\n```\n\n## References\n- Promises: [Introduction](http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/)\n- Middleclass: [Wiki](https://github.com/kikito/middleclass)\n\n## License\nCopyright (c) 2016 Valentin Funk\n```\nThe MIT License\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvalentinfunk%2Flibk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvalentinfunk%2Flibk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvalentinfunk%2Flibk/lists"}