From b5d23f28ac017bfe3f9054a93274b89ec4f302ec Mon Sep 17 00:00:00 2001 From: silverqx Date: Tue, 23 Apr 2024 19:52:09 +0200 Subject: [PATCH] Deploy website - based on 047cfe9de03a788202396f2a35ed333c666fe88f --- 404.html | 4 ++-- assets/js/{0ab078a9.34078f5e.js => 0ab078a9.b12188c8.js} | 2 +- assets/js/{59b1a96c.6afbbfdf.js => 59b1a96c.79c5818c.js} | 2 +- assets/js/{8a8faf8d.3f5122a9.js => 8a8faf8d.2ff78836.js} | 2 +- assets/js/{feaee7f3.d9eea7da.js => feaee7f3.700d4636.js} | 2 +- .../{runtime~main.767f632f.js => runtime~main.dd99a9a8.js} | 2 +- building/hello-world.html | 6 +++--- building/migrations.html | 6 +++--- building/tinyorm.html | 6 +++--- database/getting-started.html | 4 ++-- database/migrations.html | 4 ++-- database/query-builder.html | 4 ++-- database/seeding.html | 4 ++-- dependencies.html | 4 ++-- features-summary.html | 4 ++-- index.html | 6 +++--- search.html | 4 ++-- sponsors.html | 4 ++-- supported-compilers.html | 4 ++-- tinydrivers/getting-started.html | 4 ++-- tinyorm/casts.html | 4 ++-- tinyorm/collections.html | 4 ++-- tinyorm/getting-started.html | 4 ++-- tinyorm/relationships.html | 4 ++-- tinyorm/serialization.html | 4 ++-- 25 files changed, 49 insertions(+), 49 deletions(-) rename assets/js/{0ab078a9.34078f5e.js => 0ab078a9.b12188c8.js} (99%) rename assets/js/{59b1a96c.6afbbfdf.js => 59b1a96c.79c5818c.js} (98%) rename assets/js/{8a8faf8d.3f5122a9.js => 8a8faf8d.2ff78836.js} (99%) rename assets/js/{feaee7f3.d9eea7da.js => feaee7f3.700d4636.js} (99%) rename assets/js/{runtime~main.767f632f.js => runtime~main.dd99a9a8.js} (79%) diff --git a/404.html b/404.html index 987d67650..a9fceb6cf 100644 --- a/404.html +++ b/404.html @@ -14,13 +14,13 @@ - +
Skip to main content

Page Not Found

We could not find what you were looking for.

Please contact the owner of the site that linked you to the original URL and let them know their link is broken.

- + \ No newline at end of file diff --git a/assets/js/0ab078a9.34078f5e.js b/assets/js/0ab078a9.b12188c8.js similarity index 99% rename from assets/js/0ab078a9.34078f5e.js rename to assets/js/0ab078a9.b12188c8.js index cdb586c89..81479276c 100644 --- a/assets/js/0ab078a9.34078f5e.js +++ b/assets/js/0ab078a9.b12188c8.js @@ -1 +1 @@ -"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[969],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),i=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,i.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>f});var a=n(7462),i=n(7294),l=n(6010),r=n(2466),o=n(6550),d=n(1980),p=n(7392),m=n(12);function s(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:i}}=e;return{value:t,label:n,attributes:a,default:i}}))}function k(e){const{values:t,children:n}=e;return(0,i.useMemo)((()=>{const e=t??s(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function u(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function N(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,d._X)(l),(0,i.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function c(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=k(e),[r,o]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!u({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[d,p]=N({queryString:n,groupId:a}),[s,c]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,m.Nk)(n);return[a,(0,i.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),h=(()=>{const e=d??s;return u({value:e,tabValues:l})?e:null})();(0,i.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!u({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),c(e)}),[p,c,l]),tabValues:l}}var h=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:d,tabValues:p}=e;const m=[],{blockElementScrollPositionUntilNextRender:s}=(0,r.o5)(),k=e=>{const t=e.currentTarget,n=m.indexOf(t),a=p[n].value;a!==o&&(s(t),d(a))},u=e=>{let t=null;switch(e.key){case"Enter":k(e);break;case"ArrowRight":{const n=m.indexOf(e.currentTarget)+1;t=m[n]??m[0];break}case"ArrowLeft":{const n=m.indexOf(e.currentTarget)-1;t=m[n]??m[m.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:r}=e;return i.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>m.push(e),onKeyDown:u,onClick:k},r,{className:(0,l.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":o===t})}),n??t)})))}function C(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function y(e){const t=c(e);return i.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},i.createElement(g,(0,a.Z)({},e,t)),i.createElement(C,(0,a.Z)({},e,t)))}function f(e){const t=(0,h.Z)();return i.createElement(y,(0,a.Z)({key:String(t)},e))}},5178:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),i=n(6550);const l={apiTable:"apiTable_flxF"};const r=(0,a.forwardRef)(((e,t)=>{let{name:n,children:l}=e;const r=function(e){let t=e;for(;(0,a.isValidElement)(t);)[t]=a.Children.toArray(t.props.children);return t}(l),o=n?`#${n}-${r}`:`#${r}`,d=(0,i.k6)();return a.createElement("tr",{id:r,tabIndex:0,ref:d.location.hash===o?t:void 0,onClick:()=>{d.push(o)},onKeyDown:e=>{"Enter"===e.key&&d.push(o)}},l.props.children)}));function o(e){let{children:t,name:n}=e;const[i,o]=a.Children.toArray(t.props.children),d=(0,a.useRef)(null);(0,a.useEffect)((()=>{d.current?.focus()}),[d]);const p=a.Children.map(o.props.children,(e=>a.createElement(r,{name:n,ref:d},e)));return a.createElement("table",{className:l.apiTable},i,a.createElement("tbody",null,p))}},2044:(e,t,n)=>{n.d(t,{$t:()=>s,Ae:()=>h,C:()=>N,DK:()=>b,Fo:()=>o,Fs:()=>i,IM:()=>c,IZ:()=>a,RS:()=>_,VE:()=>g,Wg:()=>y,_A:()=>p,al:()=>T,jk:()=>u,js:()=>d,of:()=>m,q5:()=>r,qb:()=>f,vk:()=>k,wU:()=>l,zg:()=>C});const a="shell",i="database",l="application",r="bash",o="pwsh",d="zsh",p="maria",m="mysql",s="postgres",k="sqlite",u="application",N="bash",c="pwsh",h="zsh",b="MariaDB",g="MySQL",C="PostgreSQL",y="SQLite",f="tinyorm.org",T="$HOME/Code/c/",_="$env:USERPROFILE\\Code\\c\\"},4355:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),i=n(9482);function l(){const e=(0,a.useContext)(i.Z);if(null!=e)return e;throw new Error("useRootFolderContext is used outside of Layout component.")}},6005:(e,t,n)=>{n.d(t,{AE:()=>o,EA:()=>r,em:()=>p,go:()=>d,mT:()=>m,we:()=>s});var a=n(4355),i=n(2389),l=n(2044);const r=function(e,t){return void 0===t&&(t=!0),k((0,a.Z)().rootFolder[e]??p(e),e,t)},o=()=>(0,a.Z)().rootFolder[l.wU]??p(l.wU),d=function(e,t){if(void 0===t&&(t=!0),null==e)throw new Error("The groupId in the applicationFolderPath() can not be empty.");const n=t||e!==l.Fo?"/":"\\";return k(r(e)+n+o(),e,t)};function p(e){if(null==e)throw new Error("The groupId in the folderDefaultValue() can not be empty.");if(!(0,i.Z)())return"";switch(e){case l.Fo:return l.RS;case l.q5:return l.al;case l.wU:return l.qb;default:throw new Error(`No default value for '${e}' groupId in the folderDefaultValue().`)}}function m(e){return e===l.wU}function s(e,t){if(null==t||""===t)return t;const n="$ENV{$1}$2";switch(e){case l.Fo:return N(t).replace(/\$env:(.+?)(\/.*)/,n);case l.q5:return t.replace(/\$(.+?)(\/.*)/,n);default:throw new Error(`Unsupported shell type '${e}' in the convertToCmakeEnvVariable().`)}}function k(e,t,n){if(void 0===n&&(n=!0),null==e||""===e)return e;if(t!==l.Fo)return u(e);const a=u(e);return n?N(a):function(e){return null==e||""===e?e:e.replaceAll(/\/+/g,"\\")}(a)}function u(e){return null==e||""===e?e:e.replace(/[/\\]+$/,"")}function N(e){return null==e||""===e?e:e.replaceAll(/\\+(?! )/g,"/")}},4040:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>v,contentTitle:()=>T,default:()=>R,frontMatter:()=>f,metadata:()=>_,toc:()=>O});var a=n(7462),i=n(7294),l=n(3905),r=n(5178),o=n(7693),d=n(5162),p=n(4866),m=n(5697),s=n.n(m),k=n(6005);function u(e){let{groupId:t}=e;return i.createElement("span",null,(0,k.go)(t))}u.propTypes={groupId:s().string.isRequired};const N=u;var c=n(6010),h=n(4355);const b={rootFolderInput:"rootFolderInput_ottS",input:"input_OR7e",application:"application_fjej"};function g(e){let{groupId:t,label:n}=e;const{rootFolder:a,setRootFolder:l}=(0,h.Z)(),r=(0,k.mT)(t),o=r?"application":"root",d=r?"\nThis folder name is common for all shells (eg. pwsh, bash, ...)":"";return i.createElement("form",{name:"tinyorm-root-folder-form",className:(0,c.Z)(b.rootFolderInput,b[t],t),onSubmit:e=>{e.preventDefault(),e.stopPropagation()}},i.createElement("input",{name:"tinyorm-root-folder-input",className:(0,c.Z)(b.input,b[t],t),placeholder:`Enter ${o} folder...`,title:`This ${o} folder will be used in all ${n} examples at tinyorm.org${d}`,onChange:e=>{l(t,e.target.value)},value:a[t]??(0,k.em)(t)}))}g.propTypes={groupId:s().string.isRequired,label:s().string.isRequired};const C=g;var y=n(2044);const f={sidebar_position:0,sidebar_label:"TinyORM",hide_table_of_contents:!0,description:"How to compile the TinyORM C++ library on Windows and Linux.",keywords:["c++ orm","building","tinyorm"]},T="Building: TinyORM",_={unversionedId:"building/tinyorm",id:"building/tinyorm",title:"Building: TinyORM",description:"How to compile the TinyORM C++ library on Windows and Linux.",source:"@site/docs/building/tinyorm.mdx",sourceDirName:"building",slug:"/building/tinyorm",permalink:"/building/tinyorm",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/building/tinyorm.mdx",tags:[],version:"current",sidebarPosition:0,frontMatter:{sidebar_position:0,sidebar_label:"TinyORM",hide_table_of_contents:!0,description:"How to compile the TinyORM C++ library on Windows and Linux.",keywords:["c++ orm","building","tinyorm"]},sidebar:"tinyormSidebar",previous:{title:"Getting Started",permalink:"/tinydrivers/getting-started"},next:{title:"Hello world",permalink:"/building/hello-world"}},v={},O=[{value:"Introduction",id:"introduction",level:2},{value:"Common Prerequisites",id:"common-prerequisites",level:4},{value:"Windows Prerequisites",id:"windows-prerequisites",level:4},{value:"Build environment scripts",id:"build-environment-scripts",level:5},{value:"Allow symbolic links unprivileged",id:"allow-symbolic-links-unprivileged",level:5},{value:"Folders structure",id:"folders-structure",level:2},{value:"Getting started",id:"getting-started",level:2},{value:"vcpkg",id:"vcpkg",level:2},{value:"Set up vcpkg environment",id:"set-up-vcpkg-environment",level:4},{value:"C preprocessor macros",id:"c-preprocessor-macros",level:2},{value:"Building with CMake",id:"building-with-cmake",level:2},{value:"Configure & Build (cmake)",id:"configure-and-build-cmake",level:3},{value:"CMake STRICT_MODE option",id:"cmake-strict_mode-option",level:5},{value:"Build TinyORM",id:"build-tinyorm",level:4},{value:"CMake build options",id:"cmake-build-options",level:3},{value:"Consume TinyOrm library (cmake)",id:"consume-tinyorm-library-cmake",level:3},{value:"Building with qmake",id:"building-with-qmake",level:2},{value:"Install dependencies",id:"install-dependencies",level:3},{value:"Configure & Build (qmake)",id:"configure-and-build-qmake",level:3},{value:"Open QtCreator IDE",id:"open-qtcreator-ide",level:4},{value:"Configure TinyORM",id:"configure-tinyorm",level:4},{value:"Auto-configuration and tiny_dotenv",id:"auto-configuration-and-tiny_dotenv",level:5},{value:"Manual configuration (conf.pri)",id:"manual-configuration-confpri",level:5},{value:"Opening TinyORM.pro (main project file)",id:"opening-tinyormpro-main-project-file",level:5},{value:"Build TinyORM",id:"build-tinyorm-1",level:4},{value:"qmake build options",id:"qmake-build-options",level:3},{value:"Consume TinyOrm library (qmake)",id:"consume-tinyorm-library-qmake",level:3},{value:"Requirements",id:"requirements",level:4},{value:"QMAKEFEATURES",id:"qmakefeatures",level:5},{value:"Variables affecting TinyOrm.pri",id:"variables-affecting-tinyormpri",level:5},{value:"Manual configuration examples",id:"manual-configuration-examples",level:5},{value:"Auto-configuration internals",id:"auto-configuration-internals",level:3},{value:"Environment files",id:"environment-files",level:4},{value:"Partial guessing of the TINYORM_BUILD_TREE",id:"partial-guessing-of-the-tinyorm_build_tree",level:4},{value:"Manual configuration internals",id:"manual-configuration-internals",level:3},{value:"Ccache support",id:"ccache-support",level:2}],I={toc:O},M="wrapper";function R(e){let{components:t,...i}=e;return(0,l.kt)(M,(0,a.Z)({},I,i,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("h1",{id:"building-tinyorm"},"Building: TinyORM"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#introduction"},"Introduction"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#common-prerequisites"},"Common Prerequisites")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#windows-prerequisites"},"Windows Prerequisites")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#folders-structure"},"Folders structure")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#getting-started"},"Getting started")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#vcpkg"},"vcpkg")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#c-preprocessor-macros"},"C preprocessor macros")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#building-with-cmake"},"Building with CMake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#configure-and-build-cmake"},"Configure & Build")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#cmake-build-options"},"CMake build options")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#consume-tinyorm-library-cmake"},"Consume TinyOrm library")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#building-with-qmake"},"Building with qmake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#install-dependencies"},"Install dependencies")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#configure-and-build-qmake"},"Configure & Build")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#qmake-build-options"},"qmake build options")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#consume-tinyorm-library-qmake"},"Consume TinyOrm library")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#auto-configuration-internals"},"Auto-configuration internals"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#environment-files"},"Environment files")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#manual-configuration-internals"},"Manual configuration internals")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#ccache-support"},"Ccache support"))),(0,l.kt)("h2",{id:"introduction"},"Introduction"),(0,l.kt)("p",null,"The build systems supported out of the box are ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake"),"."),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"All examples below assume that ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh")," runs on ",(0,l.kt)("inlineCode",{parentName:"p"},"Windows")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"bash")," runs on ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux"),".")),(0,l.kt)("h4",{id:"common-prerequisites"},"Common Prerequisites"),(0,l.kt)("p",null,"Install the required ",(0,l.kt)("a",{parentName:"p",href:"/dependencies"},"dependencies")," before starting."),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"QSqlDatabase")," depends on ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," from ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt v6.5.3")," so you must create the ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," instance before you will call anything from the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. \ud83e\udee4 The change was made ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/qt/qtbase/commit/8d2bdc9cd5482eace12ba7e45304857bd24db0e6#diff-1d355c25c0b0eddec2be48253407780c4dc510d986739aec61e1ec892ccaf86e"},"here"),".")),(0,l.kt)("h4",{id:"windows-prerequisites"},"Windows Prerequisites"),(0,l.kt)("h5",{id:"build-environment-scripts"},"Build environment scripts"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Visual Studio")," does not provide ",(0,l.kt)("inlineCode",{parentName:"p"},"vcvars")," scripts for ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh"),", you can use ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/tools/vcvars64.ps1"},(0,l.kt)("inlineCode",{parentName:"a"},"vcvars64.ps1"))," provided by ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," in the ",(0,l.kt)("inlineCode",{parentName:"p"},"tools/")," folder. Place them on the ",(0,l.kt)("inlineCode",{parentName:"p"},"$env:Path")," user/system path and they will be available system-wide."),(0,l.kt)("p",null,"The same is true for the ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt Framework"),", it doesn't provide ",(0,l.kt)("inlineCode",{parentName:"p"},"qtenv")," scripts for ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh")," too. You can create your own script, place it on the ",(0,l.kt)("inlineCode",{parentName:"p"},"$env:Path")," user/system path and it will be available system-wide."),(0,l.kt)("p",null,"Here is one simple example for ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh"),"."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:"qtenv6.ps1",label:"qtenv6.ps1",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},"Write-Host 'Setting up environment for Qt 6.7.0 usage...' -ForegroundColor Magenta\n$env:Path = 'C:\\Qt\\6.7.0\\msvc2019_64\\bin;' + $env:Path\n. E:\\dotfiles\\bin\\vcvars64.ps1\n"))),(0,l.kt)(d.Z,{value:"qtenv5.ps1",label:"qtenv5.ps1",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},"Write-Host 'Setting up environment for Qt 5.15.2 usage...' -ForegroundColor Magenta\n$env:Path = 'C:\\Qt\\5.15.2\\msvc2019_64\\bin;' + $env:Path\n. E:\\dotfiles\\bin\\vcvars64.ps1\n")))),(0,l.kt)("p",null,"And here for ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux"),"."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:"qtenv6",label:"qtenv6",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"echo 'Setting up environment for Qt 6.7.0 usage...'\n\nexport PATH=/opt/Qt/6.7.0/gcc_64/bin${PATH:+:}$PATH\nexport LD_LIBRARY_PATH=/opt/Qt/6.7.0/gcc_64/lib${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH\n"))),(0,l.kt)(d.Z,{value:"qtenv5",label:"qtenv5",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"echo 'Setting up environment for Qt 5.15.2 usage...'\n\nexport PATH=/opt/Qt/5.15.2/gcc_64/bin${PATH:+:}$PATH\nexport LD_LIBRARY_PATH=/opt/Qt/5.15.2/gcc_64/lib${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH\n")))),(0,l.kt)("h5",{id:"allow-symbolic-links-unprivileged"},"Allow symbolic links unprivileged"),(0,l.kt)("p",null,"Open ",(0,l.kt)("inlineCode",{parentName:"p"},"Local Security Policy"),", go to ",(0,l.kt)("inlineCode",{parentName:"p"},"Local Policies - User Rights Assignment"),", open ",(0,l.kt)("inlineCode",{parentName:"p"},"Create symbolic links")," and add your user account or user group, restart when it doesn't apply immediately."),(0,l.kt)("h2",{id:"folders-structure"},"Folders structure"),(0,l.kt)("p",null,"All ",(0,l.kt)("inlineCode",{parentName:"p"},"tinyorm.org")," examples are based on the following folders structure. The ",(0,l.kt)("inlineCode",{parentName:"p"},"tom")," folder will contain a ",(0,l.kt)("a",{parentName:"p",href:"/building/migrations"},"migrations console application"),"."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can set the root and application folder paths in the form below and they will be used across the whole ",(0,l.kt)("a",{parentName:"p",href:"http://www.tinyorm.org"},"www.tinyorm.org")," website. \ud83e\udd73 The pwsh shell is supposed to use on Windows and the bash shell on Linux, but it is not a requirement.")),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,className:"tiny-tree",mdxType:"TabItem"},(0,l.kt)("div",{className:"tiny-root-folder-info-wrapper"},(0,l.kt)("span",{className:"tiny-root-folder-info-prefix"},"Current pwsh path"),"\xa0",(0,l.kt)(N,{groupId:y.Fo,mdxType:"RootFolder"})),(0,l.kt)(C,{groupId:y.Fo,label:y.IM,mdxType:"RootFolderInput"}),(0,l.kt)(C,{groupId:y.wU,label:y.jk,mdxType:"RootFolderInput"}),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-text"},"\n\n\n\u251c\u2500\u2500\n\u2502 \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld-builds-cmake/\n\u2502 | | \u2514\u2500\u2500 build-debug/\n\u2502 | \u2514\u2500\u2500 HelloWorld-builds-qmake/\n\u2502 | \u2514\u2500\u2500 build-debug/\n\u2502 \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM-builds-cmake/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-debug/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-release/\n\u2502 | \u2502 \u2514\u2500\u2500 build-clang-debug/\n\u2502 | \u2514\u2500\u2500 TinyORM-builds-qmake/\n\u2502 | \u251c\u2500\u2500 build-debug/\n\u2502 | \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug/\n\u2502 | \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_MSYS2_UCRT64_64bit-Release/\n\u2502 \u2514\u2500\u2500 tom/\n\u2502 \u251c\u2500\u2500 tom/\n\u2502 \u2502 \u2514\u2500\u2500 database/\n\u2502 \u2502 \u251c\u2500\u2500 migrations/\n\u2502 \u2502 \u251c\u2500\u2500 seeders/\n\u2502 \u2502 \u251c\u2500\u2500 migrations.pri\n\u2502 \u2502 \u2514\u2500\u2500 seeders.pri\n\u2502 \u251c\u2500\u2500 tom-builds-cmake/\n\u2502 \u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/\n\u2502 \u2514\u2500\u2500 tom-builds-qmake/\n\u2502 \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_3_MSYS2_UCRT64_64bit-Release/\n\u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/\n\u251c\u2500\u2500 tmp/\n\u2514\u2500\u2500 vcpkg/\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,className:"tiny-tree",mdxType:"TabItem"},(0,l.kt)("div",{className:"tiny-root-folder-info-wrapper"},(0,l.kt)("span",{className:"tiny-root-folder-info-prefix"},"Current bash path"),"\xa0",(0,l.kt)(N,{groupId:y.q5,mdxType:"RootFolder"})),(0,l.kt)(C,{groupId:y.q5,label:y.C,mdxType:"RootFolderInput"}),(0,l.kt)(C,{groupId:y.wU,label:y.wU,mdxType:"RootFolderInput"}),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-text"},"\n\n\n\u251c\u2500\u2500\n\u2502 \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld-builds-cmake/\n\u2502 | | \u2514\u2500\u2500 build-debug/\n\u2502 | \u2514\u2500\u2500 HelloWorld-builds-qmake/\n\u2502 | \u2514\u2500\u2500 build-debug/\n\u2502 \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM-builds-cmake/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-debug/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-release/\n\u2502 | \u2502 \u2514\u2500\u2500 build-clang-debug/\n\u2502 | \u2514\u2500\u2500 TinyORM-builds-qmake/\n\u2502 | \u251c\u2500\u2500 build-debug/\n\u2502 | \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_GCC_64bit-Debug/\n\u2502 | \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_clang13_64bit_ccache-Release/\n\u2502 \u2514\u2500\u2500 tom/\n\u2502 \u251c\u2500\u2500 tom/\n\u2502 \u2502 \u2514\u2500\u2500 database/\n\u2502 \u2502 \u251c\u2500\u2500 migrations/\n\u2502 \u2502 \u251c\u2500\u2500 seeders/\n\u2502 \u2502 \u251c\u2500\u2500 migrations.pri\n\u2502 \u2502 \u2514\u2500\u2500 seeders.pri\n\u2502 \u251c\u2500\u2500 tom-builds-cmake/\n\u2502 \u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_clang14_64bit_ccache-Debug/\n\u2502 \u2514\u2500\u2500 tom-builds-qmake/\n\u2502 \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_GCC_64bit-Debug/\n\u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_clang14_64bit_ccache-Release/\n\u251c\u2500\u2500 tmp/\n\u2514\u2500\u2500 vcpkg/\n")))),(0,l.kt)("admonition",{type:"danger"},(0,l.kt)("p",{parentName:"admonition"},"Avoid paths with spaces with the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system, it will not compile.")),(0,l.kt)("a",{id:"qtcreator-default-build-directory"}),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can force the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described above."),(0,l.kt)("p",{parentName:"admonition"},"To generate the required folders structure set the ",(0,l.kt)("inlineCode",{parentName:"p"},"Settings")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Build & Run")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Default Build Properties")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Default build directory")," to:",(0,l.kt)("br",null),"\n",(0,l.kt)("inlineCode",{parentName:"p"},'../%{Project:Name}-builds-%{BuildSystem:Name}/%{JS: Util.asciify("build-%{Project:Name}-%{Kit:FileSystemName}-%{BuildConfig:Name}")}'))),(0,l.kt)("h2",{id:"getting-started"},"Getting started"),(0,l.kt)("p",null,"Prepare compilation environment, we need to put the Qt Framework and Visual Studio MSVC compiler on the path on Windows. The compiler is already on the path on Linux and you can export ",(0,l.kt)("inlineCode",{parentName:"p"},"PATH")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," for Qt Framework, or use our ",(0,l.kt)("inlineCode",{parentName:"p"},"qtenvX")," scripts described above."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`mkdir ${(0,k.EA)(y.Fo)}\ncd ${(0,k.EA)(y.Fo)}\n$env:Path = 'C:\\Qt\\6.7.0\\msvc2019_64\\bin;' + $env:Path\nvcvars64.ps1`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`mkdir -p ${(0,k.EA)(y.q5)}\ncd ${(0,k.EA)(y.q5)}\nexport PATH=/opt/Qt/6.7.0/gcc_64/bin\${PATH:+:}$PATH\nexport LD_LIBRARY_PATH=/opt/Qt/6.7.0/gcc_64/lib\${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH`))),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can also use the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/tools/Add-FolderOnPath.ps1"},(0,l.kt)("inlineCode",{parentName:"a"},"tools/Add-FolderOnPath.ps1"))," pwsh script to fastly prepend a path or ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd")," on the system ",(0,l.kt)("inlineCode",{parentName:"p"},"PATH"),".")),(0,l.kt)("h2",{id:"vcpkg"},"vcpkg"),(0,l.kt)("p",null,"Installing the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," is highly recommended, it simplifies installation of the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," dependencies."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},"git clone git@github.com:microsoft/vcpkg.git\ncd vcpkg\n.\\bootstrap-vcpkg.bat\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"git clone git@github.com:microsoft/vcpkg.git\ncd vcpkg\n./bootstrap-vcpkg.sh\n")))),(0,l.kt)("p",null,"Add ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," on the system path, add the following to the ",(0,l.kt)("inlineCode",{parentName:"p"},".bashrc")," or ",(0,l.kt)("inlineCode",{parentName:"p"},".zshrc")," on Linux."),(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export PATH=${(0,k.EA)(y.q5)}/vcpkg\${PATH:+:}$PATH`),(0,l.kt)("p",null,"On Windows, open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Environment variables")," dialog and add ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," on the user ",(0,l.kt)("inlineCode",{parentName:"p"},"PATH"),"."),(0,l.kt)("p",null,"Or you can export it for the current session only."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,k.EA)(y.Fo,!1)}\\vcpkg;" + $env:Path`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export PATH=${(0,k.EA)(y.q5)}/vcpkg\${PATH:+:}$PATH`))),(0,l.kt)("h4",{id:"set-up-vcpkg-environment"},"Set up ",(0,l.kt)("inlineCode",{parentName:"h4"},"vcpkg")," environment"),(0,l.kt)("p",null,"To export ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," environment variables globally, add it to the ",(0,l.kt)("inlineCode",{parentName:"p"},".bashrc")," or ",(0,l.kt)("inlineCode",{parentName:"p"},".zshrc")," on Linux, and you can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"Environment variables")," dialog on Windows."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash",metastring:"title='Linux'",title:"'Linux'"},'export VCPKG_DEFAULT_TRIPLET=x64-linux\n#export VCPKG_DEFAULT_HOST_TRIPLET=x64-linux\nexport VCPKG_MAX_CONCURRENCY=11\nexport VCPKG_OVERLAY_PORTS="$HOME/.local/share/vcpkg/ports"\nexport VCPKG_OVERLAY_TRIPLETS="$HOME/.local/share/vcpkg/triplets"\nexport VCPKG_ROOT="$HOME/Code/c/vcpkg"\n')),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"It is recommended to define these variables globally because the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system are able to detect the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," installation from them so you don't have to configure them manually to detect the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," installation.")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"On Windows, it's always better to create these types of variables as user variables instead of system variables in the ",(0,l.kt)("inlineCode",{parentName:"p"},"Environment variables")," dialog.")),(0,l.kt)("h2",{id:"c-preprocessor-macros"},"C preprocessor macros"),(0,l.kt)("p",null,"The following table summarizes all the C preprocessor macros defined in the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. These C macros are configured by ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build systems. They are not sorted alphabetically, but they are sorted by how significant they are."),(0,l.kt)("p",null,"In the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," build system, all the C macros are auto-detected / auto-configured or controlled by ",(0,l.kt)("a",{parentName:"p",href:"#cmake-build-options"},(0,l.kt)("inlineCode",{parentName:"a"},"CMake build options")),", so you don't have to care too much about them."),(0,l.kt)("p",null,"In the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build is important whether you are building ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library or you are building your application and linking against ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. When you are building the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library, all the C macros are auto-detected / auto-configured or controlled by ",(0,l.kt)("a",{parentName:"p",href:"#qmake-build-options"},(0,l.kt)("inlineCode",{parentName:"a"},"qmake build options")),", so you don't have to care too much about them."),(0,l.kt)("p",null,"But a special situation is when you are building your application / library and you are linking against ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. In this particular case, you must configure all these C macros manually! For this reason, the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/qmake/TinyOrm.pri"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyOrm.pri"))," has been created, so that's not a big deal either. Little more info ",(0,l.kt)("a",{parentName:"p",href:"#consume-tinyorm-library-qmake"},"here"),"."),(0,l.kt)("div",{id:"apitable-c-macros"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"C Macro Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_LINKING_SHARED")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("u",null,(0,l.kt)("strong",{parentName:"td"},"Must"))," be defined when you are linking against ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," shared build (",(0,l.kt)("inlineCode",{parentName:"td"},"dll")," library), exported classes and functions will be tagged with ",(0,l.kt)("inlineCode",{parentName:"td"},"__declspec(dllimport)")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc")," and ",(0,l.kt)("inlineCode",{parentName:"td"},'visibility("default")')," on ",(0,l.kt)("inlineCode",{parentName:"td"},"GCC >= 4"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_BUILDING_SHARED")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined when ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," is built as a ",(0,l.kt)("inlineCode",{parentName:"td"},"dll")," library (shared build).")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DEBUG")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the debug build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_NO_DEBUG")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the release build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DEBUG_SQL")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the debug build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_NO_DEBUG_SQL")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the release build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_MYSQL_PING")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::MySqlConnection::pingDatabase()")," method.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#mysql_ping"},(0,l.kt)("inlineCode",{parentName:"a"},"mysql_ping"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#MYSQL_PING"},(0,l.kt)("inlineCode",{parentName:"a"},"MYSQL_PING"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DISABLE_ORM")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," source code, when this macro is ",(0,l.kt)("inlineCode",{parentName:"td"},"defined"),", then only the ",(0,l.kt)("inlineCode",{parentName:"td"},"query builder")," without ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM")," is compiled. Also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," unit tests.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#disable_orm"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_orm"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#ORM"},(0,l.kt)("inlineCode",{parentName:"a"},"ORM"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled ",(0,l.kt)("small",null,"(qmake)")," / disabled ",(0,l.kt)("small",null,"(cmake)"),"."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_EXTERN_CONSTANTS")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined when extern constants are used. Extern constants are enabled by default for shared builds and disabled for static builds.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Described at ",(0,l.kt)("a",{parentName:"td",href:"#extern_constants"},(0,l.kt)("inlineCode",{parentName:"a"},"qmake"))," / ",(0,l.kt)("a",{parentName:"td",href:"#INLINE_CONSTANTS"},(0,l.kt)("inlineCode",{parentName:"a"},"CMake"))," how it works."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_INLINE_CONSTANTS")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined when global inline constants are used.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#inline_constants"},(0,l.kt)("inlineCode",{parentName:"a"},"inline_constants"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#INLINE_CONSTANTS"},(0,l.kt)("inlineCode",{parentName:"a"},"INLINE_CONSTANTS"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_TESTS_CODE")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable code needed by unit tests, eg. connection overriding in the ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::Tiny::Model"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#build_tests"},(0,l.kt)("inlineCode",{parentName:"a"},"build_tests"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#BUILD_TESTS"},(0,l.kt)("inlineCode",{parentName:"a"},"BUILD_TESTS"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DISABLE_THREAD_LOCAL")),(0,l.kt)("td",{parentName:"tr",align:null},"Remove all ",(0,l.kt)("a",{parentName:"td",href:"https://en.cppreference.com/w/c/language/storage_duration"},(0,l.kt)("inlineCode",{parentName:"a"},"thread_local"))," storage duration specifiers, it disables multi-threading support.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#disable_thread_local"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_thread_local"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#DISABLE_THREAD_LOCAL"},(0,l.kt)("inlineCode",{parentName:"a"},"DISABLE_THREAD_LOCAL"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYTOM_MIGRATIONS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Default migrations path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:migration")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/migrations")," ",(0,l.kt)("small",null,"(relative to the pwd)")),(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined by ",(0,l.kt)("a",{parentName:"td",href:"#TOM_MIGRATIONS_DIR"},(0,l.kt)("inlineCode",{parentName:"a"},"TOM_MIGRATIONS_DIR"))," ",(0,l.kt)("small",null,"(cmake)")," configuration build option.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(qmake note) You can use ",(0,l.kt)("inlineCode",{parentName:"td"},'DEFINES += TINYTOM_MIGRATIONS_DIR="\\"database/migrations\\""')," on the command-line or set it in the ",(0,l.kt)("strong",{parentName:"td"},"main")," ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L65-L70"},(0,l.kt)("inlineCode",{parentName:"a"},"conf.pri"))," file.")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYTOM_MODELS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Default models path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:model")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/models")," ",(0,l.kt)("small",null,"(relative to the pwd)")),(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined by ",(0,l.kt)("a",{parentName:"td",href:"#TOM_MODELS_DIR"},(0,l.kt)("inlineCode",{parentName:"a"},"TOM_MODELS_DIR"))," ",(0,l.kt)("small",null,"(cmake)")," configuration build option.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(qmake note) You can use ",(0,l.kt)("inlineCode",{parentName:"td"},'DEFINES += TINYTOM_MODELS_DIR="\\"database/models\\""')," on the command-line or set it in the ",(0,l.kt)("strong",{parentName:"td"},"main")," ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L72-L73"},(0,l.kt)("inlineCode",{parentName:"a"},"conf.pri"))," file.")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYTOM_SEEDERS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Default seeders path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:seeder")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/seeders")," ",(0,l.kt)("small",null,"(relative to the pwd)")),(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined by ",(0,l.kt)("a",{parentName:"td",href:"#TOM_SEEDERS_DIR"},(0,l.kt)("inlineCode",{parentName:"a"},"TOM_SEEDERS_DIR"))," ",(0,l.kt)("small",null,"(cmake)")," configuration build option.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(qmake note) You can use ",(0,l.kt)("inlineCode",{parentName:"td"},'DEFINES += TINYTOM_SEEDERS_DIR="\\"database/seeders\\""')," on the command-line or set it in the ",(0,l.kt)("strong",{parentName:"td"},"main")," ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L75-L76"},(0,l.kt)("inlineCode",{parentName:"a"},"conf.pri"))," file.")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_USING_PCH")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined if building with precompiled headers.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Controlled by ",(0,l.kt)("a",{parentName:"td",href:"#precompile_header"},(0,l.kt)("inlineCode",{parentName:"a"},"qmake"))," / ",(0,l.kt)("a",{parentName:"td",href:"#CMAKE_DISABLE_PRECOMPILE_HEADERS"},(0,l.kt)("inlineCode",{parentName:"a"},"CMake")),"."))))))),(0,l.kt)("h2",{id:"building-with-cmake"},"Building with CMake"),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"If something is not clear, you can still look at GitHub Action ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/.github/workflows"},(0,l.kt)("inlineCode",{parentName:"a"},"workflows"))," how a building is done.")),(0,l.kt)("p",null,"First, create a basic folder structure and then clone the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.Fo)}\nmkdir ${(0,k.AE)()}/TinyORM/TinyORM-builds-cmake/build-debug\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.q5)}\nmkdir -p ${(0,k.AE)()}/TinyORM/TinyORM-builds-cmake/build-debug\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`))),(0,l.kt)("h3",{id:"configure-and-build-cmake"},"Configure & Build ",(0,l.kt)("small",null,"(cmake)")),(0,l.kt)("p",null,"Now you are ready to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd TinyORM-builds-cmake/build-debug\n")),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cmake.exe \`\n-S "${(0,k.go)(y.Fo)}/TinyORM/TinyORM" \`\n-B "${(0,k.go)(y.Fo)}/TinyORM/TinyORM-builds-cmake/build-debug" \`\n-G 'Ninja' \`\n-D CMAKE_BUILD_TYPE:STRING='Debug' \`\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,k.EA)(y.Fo)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \`\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,k.EA)(y.Fo)}/tmp/TinyORM" \`\n-D BUILD_TESTS:BOOL=OFF \`\n-D MATCH_EQUAL_EXPORTED_BUILDTREE:BOOL=ON \`\n-D MYSQL_PING:BOOL=OFF \`\n-D TOM:BOOL=ON \`\n-D TOM_EXAMPLE:BOOL=OFF \`\n-D VERBOSE_CONFIGURE:BOOL=ON`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cmake \\\n-S "${(0,k.go)(y.q5)}/TinyORM/TinyORM" \\\n-B "${(0,k.go)(y.q5)}/TinyORM/TinyORM-builds-cmake/build-debug" \\\n-G 'Ninja' \\\n-D CMAKE_BUILD_TYPE:STRING='Debug' \\\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,k.EA)(y.q5)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \\\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,k.EA)(y.q5)}/tmp/TinyORM" \\\n-D VERBOSE_CONFIGURE:BOOL=ON \\\n-D BUILD_TESTS:BOOL=OFF \\\n-D MYSQL_PING:BOOL=OFF \\\n-D TOM:BOOL=ON \\\n-D TOM_EXAMPLE:BOOL=OFF \\\n-D MATCH_EQUAL_EXPORTED_BUILDTREE:BOOL=ON`))),(0,l.kt)("h5",{id:"cmake-strict_mode-option"},"CMake ",(0,l.kt)("inlineCode",{parentName:"h5"},"STRICT_MODE")," option"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," configuration option was added in ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.37.0"),". This option was added to avoid the propagation of aggressive strict warning compiler/linker options and Qt definitions from the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library to user code through the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/cmake/CommonModules/TinyCommon.cmake"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyOrm::CommonConfig"))," interface library."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," uses the strictest warning level options, virtually anything that can be enabled is enabled to produce a better code. I highly recommend enabling this option to produce better code and to follow good practices. It also helps to follow the ",(0,l.kt)("inlineCode",{parentName:"p"},"ISOCPP")," ",(0,l.kt)("a",{parentName:"p",href:"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines"},"C++ Core Guidelines")," standards."),(0,l.kt)("p",null,"If you want to enable these strict warning options in your code, you can enable the ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," configuration option and they will be propagated to your code. You can also enabled it globally using the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_STRICT_MODE")," environment variable, and the value of this environment variable will be picked up during initial CMake configuration as the default value for the ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," configuration option."),(0,l.kt)("p",null,"You can achieve the same result by manually linking against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm::CommonConfig")," interface library when the ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," is set to ",(0,l.kt)("inlineCode",{parentName:"p"},"OFF"),"."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-cmake"},"target_link_libraries( PRIVATE TinyOrm::CommonConfig)\n")),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"The recommended way is to set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_STRICT_MODE")," environment variable to ",(0,l.kt)("inlineCode",{parentName:"p"},"1")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"ON"),".")),(0,l.kt)("h4",{id:"build-tinyorm"},"Build TinyORM"),(0,l.kt)("p",null,"And build. You don't have to install it, you can use the build tree directly if you want."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target all\ncmake --install .\n")),(0,l.kt)("p",null,"Or build and install in one step."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target install\n")),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"CMake multi-config generators like ",(0,l.kt)("inlineCode",{parentName:"p"},"Ninja Multi-Config")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"Visual Studio 16 2019")," are also supported.")),(0,l.kt)("h3",{id:"cmake-build-options"},"CMake build options"),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_DRIVERS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyDrivers"))," SQL database drivers (core/common code; replaces QtSql module).")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_MYSQL_DRIVERS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," MySQL database driver.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_DRIVERS")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_SHARED_LIBS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Build as a shared/static library.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_TESTS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build TinyORM unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_TREE_DEPLOY")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Copy ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyMySql")," libraries to the root of the build tree.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"DRIVERS_TYPE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"Shared")),(0,l.kt)("td",{parentName:"tr",align:null},"How to build and link against ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," SQL database drivers.",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"Static")," value will be select by default when the ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_SHARED_LIBS")," is ",(0,l.kt)("inlineCode",{parentName:"td"},"OFF"),".",(0,l.kt)("br",null),"Supported values: ",(0,l.kt)("inlineCode",{parentName:"td"},"Shared"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"Loadable"),", and ",(0,l.kt)("inlineCode",{parentName:"td"},"Static"),(0,l.kt)("br",null),"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_DRIVERS AND BUILD_SHARED_LIBS")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"INLINE_CONSTANTS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Use inline constants instead of extern constants in the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),".",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"OFF")," is highly recommended for the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),";",(0,l.kt)("br",null),"is always ",(0,l.kt)("inlineCode",{parentName:"td"},"ON")," for the ",(0,l.kt)("inlineCode",{parentName:"td"},"static build"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_SHARED_LIBS")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"MSVC_RUNTIME_DYNAMIC")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Use MSVC dynamic runtime library (",(0,l.kt)("inlineCode",{parentName:"td"},"-MD"),") instead of static (",(0,l.kt)("inlineCode",{parentName:"td"},"-MT"),"), also considers a Debug configuration (",(0,l.kt)("inlineCode",{parentName:"td"},"-MTd"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"-MDd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"MSVC AND NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"MYSQL_PING")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::MySqlConnection::pingDatabase()")," method.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ORM")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"disabled"),", then only the ",(0,l.kt)("inlineCode",{parentName:"td"},"query builder")," without ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM")," is compiled. Also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"STRICT_MODE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls propagation of strict compiler/linker options and Qt definitions using the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyOrm::CommonConfig")," interface library to the user code.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(highly recommended; can also be set with the ",(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_STRICT_MODE")," environment variable; described ",(0,l.kt)("a",{parentName:"td",href:"#cmake-strict_mode-option"},"here"),")"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"disabled"),", then it also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_EXAMPLE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build the ",(0,l.kt)("abbr",{title:"TinyORM Migrations"},(0,l.kt)("inlineCode",{parentName:"td"},"tom"))," console application example.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_MIGRATIONS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default migrations path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:migration")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/migrations")," ",(0,l.kt)("small",null,"(relative to the pwd)")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_MODELS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default models path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:model")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/models")," ",(0,l.kt)("small",null,"(relative to the pwd)")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_SEEDERS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default seeders path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:seeder")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/seeders")," ",(0,l.kt)("small",null,"(relative to the pwd)")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"VERBOSE_CONFIGURE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Show information about ",(0,l.kt)("inlineCode",{parentName:"td"},"PACKAGES_FOUND")," / ",(0,l.kt)("inlineCode",{parentName:"td"},"PACKAGES_NOT_FOUND")," in the CMake configure output.")))))),(0,l.kt)("p",null,"Advanced ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"DISABLE_THREAD_LOCAL")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Remove all ",(0,l.kt)("a",{parentName:"td",href:"https://en.cppreference.com/w/c/language/storage_duration"},(0,l.kt)("inlineCode",{parentName:"a"},"thread_local"))," storage duration specifiers, it disables multi-threading support.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("small",null,(0,l.kt)("inlineCode",{parentName:"td"},"MATCH_EQUAL_EXPORTED_BUILDTREE"))),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Exported package configuration from the build tree is considered to match only when ",(0,l.kt)("inlineCode",{parentName:"td"},"the build type")," of application/library that is linking against the TinyORM library ",(0,l.kt)("strong",{parentName:"td"},"is equal"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when:",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_EXPORT_PACKAGE_REGISTRY AND NOT TINY_IS_MULTI_CONFIG")))))))),(0,l.kt)("p",null,"Important ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_DISABLE_PRECOMPILE_HEADERS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Disable precompiled headers.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_CXX_COMPILER")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"auto")),(0,l.kt)("td",{parentName:"tr",align:null},"The full path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"C++")," compiler.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_CXX_COMPILER_LAUNCHER")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default compiler launcher to use for the ",(0,l.kt)("inlineCode",{parentName:"td"},"C++")," compiler.",(0,l.kt)("br",null),"Can be used to enable ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache"),", eg. ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache.exe")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"MinGW")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"/usr/bin/ccache")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"Linux"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_EXPORT_PACKAGE_REGISTRY")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable the ",(0,l.kt)("inlineCode",{parentName:"td"},"export(TinyOrm)")," command.",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," sets this variable to ",(0,l.kt)("inlineCode",{parentName:"td"},"ON")," by default.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_VERBOSE_MAKEFILE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable verbose output from Makefile builds.")))))),(0,l.kt)("h3",{id:"consume-tinyorm-library-cmake"},"Consume TinyOrm library ",(0,l.kt)("small",null,"(cmake)")),(0,l.kt)("p",null,"In your application or library ",(0,l.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file add following ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package()")," call."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-cmake",metastring:"title='CMakeLists.txt'",title:"'CMakeLists.txt'"},"find_package(TinyOrm 0.37.0 CONFIG REQUIRED)\n")),(0,l.kt)("p",null,"If the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build tree is not exported to the CMake's ",(0,l.kt)("a",{parentName:"p",href:"https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#user-package-registry"},(0,l.kt)("inlineCode",{parentName:"a"},"User Package Registry"))," then also add the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build tree or ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_INSTALL_PREFIX")," folder to the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_PREFIX_PATH"),", so CMake can find TinyORM's package configuration file during ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package(TinyOrm)")," call."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:`cmake (${y.Fo})`,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.Fo,(0,k.go)(y.Fo))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\n# installation folder - CMAKE_INSTALL_PREFIX\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.Fo,(0,k.EA)(y.Fo))}/tmp/TinyORM")`)),(0,l.kt)(d.Z,{value:y.q5,label:`cmake (${y.q5})`,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.q5,(0,k.go)(y.q5))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\n# installation folder - CMAKE_INSTALL_PREFIX\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.q5,(0,k.EA)(y.q5))}/tmp/TinyORM")`))),(0,l.kt)("p",null,"Or as an alternative, you can set ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_PREFIX_PATH")," environment variable."),(0,l.kt)("a",{id:"tinyorm-on-path-cmake"}),(0,l.kt)("p",null,"As the last thing, do not forget to add ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm0d.dll")," on the path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so your application can find it during execution."),(0,l.kt)(p.Z,{groupId:y.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,k.go)(y.Fo,!1)}\\TinyORM\\TinyORM-builds-cmake\\build-debug;" + $env:Path`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,k.go)(y.q5)}/TinyORM/TinyORM-builds-cmake/build-debug\${PATH:+:}$PATH`))),(0,l.kt)("p",null,"Now you can try the ",(0,l.kt)("a",{parentName:"p",href:"/building/hello-world#hello-world-with-cmake"},(0,l.kt)("inlineCode",{parentName:"a"},"HelloWorld CMake"))," example."),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"You can also try the ",(0,l.kt)("a",{parentName:"p",href:"/building/hello-world#fetchcontent"},(0,l.kt)("inlineCode",{parentName:"a"},"FetchContent"))," method to fastly link against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library.")),(0,l.kt)("h2",{id:"building-with-qmake"},"Building with qmake"),(0,l.kt)("p",null,"First, create a basic folder structure and then clone the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.Fo)}\nmkdir ${(0,k.AE)()}/TinyORM/TinyORM-builds-qmake\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.q5)}\nmkdir -p ${(0,k.AE)()}/TinyORM/TinyORM-builds-qmake\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`))),(0,l.kt)("h3",{id:"install-dependencies"},"Install dependencies"),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system, you have to install ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," dependencies manually. We will use the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," package manager."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../../vcpkg\n\nvcpkg search range-v3\nvcpkg search tabulate\nvcpkg install range-v3 tabulate\nvcpkg list\n")),(0,l.kt)("p",null,"On ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux"),", you can install the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," library and some other ",(0,l.kt)("a",{parentName:"p",href:"/dependencies#install-dependencies"},"dependencies")," with the package manager."),(0,l.kt)("h3",{id:"configure-and-build-qmake"},"Configure & Build ",(0,l.kt)("small",null,"(qmake)")),(0,l.kt)("h4",{id:"open-qtcreator-ide"},"Open QtCreator IDE"),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"I recommend creating a new ",(0,l.kt)("a",{parentName:"p",href:"https://doc.qt.io/qtcreator/creator-project-managing-sessions.html"},(0,l.kt)("inlineCode",{parentName:"a"},"Session"))," in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator"),", this way you will have all the examples in one place and as a bonus, everything will be in the same place when you close and reopen ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),". You can name it ",(0,l.kt)("inlineCode",{parentName:"p"},"tinyorm.org")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM examples"),", it is up to you.")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"If you are using sessions, you can use a single ",(0,l.kt)("inlineCode",{parentName:"p"},"clangd")," instance for all projects in this session in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),". One significant advantage of this method is that the ",(0,l.kt)("inlineCode",{parentName:"p"},".qtc_clangd/")," folder will not be created in the build folder, but will be stored globally in the Roaming profile. You can enable it in the ",(0,l.kt)("inlineCode",{parentName:"p"},"Settings")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"C++")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Clangd")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Sessions with a single clangd instance"),".")),(0,l.kt)("h4",{id:"configure-tinyorm"},"Configure TinyORM"),(0,l.kt)("p",null,"Now you are ready to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. There are two ways how to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library and it's the new ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configure")," feature added in ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0")," using the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files and the old way using the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files."),(0,l.kt)("h5",{id:"auto-configuration-and-tiny_dotenv"},"Auto-configuration and tiny_dotenv"),(0,l.kt)("p",null,"This is the new recommended method to auto-configure TinyORM's ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system and also the dependencies, it was added in ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0"),". You need to copy the prepared ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw).example")," file to the ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)"),". One ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," example file is prepared for each supported platform."),(0,l.kt)("p",null,"All prepared ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw).example")," files are simple and clear. You can also create a common ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," file that is included before the platform-specific ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)")," files."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.Fo)}/TinyORM/TinyORM\n\ncp .env.win32.example .env.win32`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.q5)}/TinyORM/TinyORM\n\ncp .env.unix.example .env.unix`))),(0,l.kt)("p",null,"And that is all, if you have correctly set all ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variables in this ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)")," file or you have correctly set environment variables, then the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system should be able to ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-detect")," all dependencies . \ud83d\udd25"),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("a",{parentName:"p",href:"#auto-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Auto-configuration"))," and ",(0,l.kt)("a",{parentName:"p",href:"#environment-files"},(0,l.kt)("inlineCode",{parentName:"a"},"Environment files"))," internals are described at the end to make this section more clear.")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_autoconf"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_autoconf"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_autoconf"),").")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_dotenv"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_dotenv"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_dotenv"),").")),(0,l.kt)("h5",{id:"manual-configuration-confpri"},"Manual configuration (conf.pri)"),(0,l.kt)("p",null,"This is the old method used before ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0"),". You need to copy the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri.example")," files to ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," (there are four, one for every project or sub-project) and manually update the ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"LIBS")," to configure TinyORM's ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build dependencies. This way you can override any ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build options or variables."),(0,l.kt)("p",null,"To disable the ",(0,l.kt)("a",{parentName:"p",href:"#auto-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Auto-configuration"))," feature you must define the ",(0,l.kt)("a",{parentName:"p",href:"#disable_autoconf"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_autoconf"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_autoconf"),") because from ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0")," is the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature enabled by default."),(0,l.kt)("p",null,"You can also remove all ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files or turn off the ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature using ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_dotenv"),". You can use them all at once if you want, ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," and also ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are nicely commented on, so you can see what needs to be modified."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.Fo)}/TinyORM/TinyORM\n\ncp conf.pri.example conf.pri\ncp tests/conf.pri.example tests/conf.pri\ncp tests/testdata_tom/conf.pri.example tests/testdata_tom/conf.pri\ncp examples/tom/conf.pri.example examples/tom/conf.pri`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.q5)}/TinyORM/TinyORM\n\ncp conf.pri.example conf.pri\ncp tests/conf.pri.example tests/conf.pri\ncp tests/testdata_tom/conf.pri.example tests/testdata_tom/conf.pri\ncp examples/tom/conf.pri.example examples/tom/conf.pri`))),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("a",{parentName:"p",href:"#manual-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Manual configuration"))," internals are described at the end to make this section more clear.")),(0,l.kt)("admonition",{type:"note"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Manual configuration")," is still relevant if you have any non-standard installation of the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"MySQL")," and the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature fails.")),(0,l.kt)("h5",{id:"opening-tinyormpro-main-project-file"},"Opening TinyORM.pro (main project file)"),(0,l.kt)("p",null,"Now you can open the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM.pro")," project in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),"."),(0,l.kt)("p",null,"This will open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Configure Project")," tab, select some kit and update build folder paths to meet our ",(0,l.kt)("a",{parentName:"p",href:"#folders-structure"},"folders structure")," or like you want."),(0,l.kt)("img",{src:n(6874).Z,alt:"TinyORM - QtCreator - Configure Project",width:"760"}),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can force the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described ",(0,l.kt)("a",{parentName:"p",href:"#qtcreator-default-build-directory"},"above"),".")),(0,l.kt)("p",null,"You are ready to configure build options, hit ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"5")," to open ",(0,l.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,l.kt)("inlineCode",{parentName:"p"},"Build")," in the left sidebar to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Build Settings"),", it should look similar to the following picture."),(0,l.kt)("p",null,"Disable ",(0,l.kt)("inlineCode",{parentName:"p"},"QML debugging and profiling")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt Quick Compiler"),", they are not used."),(0,l.kt)("img",{src:n(7066).Z,alt:"TinyORM - QtCreator - Build Settings",width:"760"}),(0,l.kt)("p",null,"If you want to change some ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build options, you can pass them to the ",(0,l.kt)("inlineCode",{parentName:"p"},"Build Steps")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake TinyORM.pro")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Additional arguments")," input field. It can look like this."),(0,l.kt)("img",{src:n(5705).Z,alt:"TinyORM - QtCreator - Build Settings - Additional arguments",width:"660"}),(0,l.kt)("h4",{id:"build-tinyorm-1"},"Build TinyORM"),(0,l.kt)("p",null,"Everything is ready for build, you can press ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"b")," to build the project."),(0,l.kt)("h3",{id:"qmake-build-options"},"qmake build options"),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"th"},"CONFIG")," ",(0,l.kt)("small",null,"Option Name")),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_loadable_drivers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," as a shared library and SQL database drivers (eg. ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyMySql"),") as shared libraries (",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started#the-loadable-sql-drivers-build"},(0,l.kt)("inlineCode",{parentName:"a"},"Loadable"))," modules) that are loaded at runtime using ",(0,l.kt)("inlineCode",{parentName:"td"},"LoadLibrary()")," on Windows or ",(0,l.kt)("inlineCode",{parentName:"td"},"dlopen()")," on Linux.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_mysql_driver")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," MySQL database driver.",(0,l.kt)("br",null),(0,l.kt)("small",null,"It's enabled by default when ",(0,l.kt)("inlineCode",{parentName:"td"},"build_shared_drivers"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"build_loadable_drivers"),", or ",(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")," is enabled.",(0,l.kt)("br",null),"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"build_shared_drivers")," OR ",(0,l.kt)("inlineCode",{parentName:"td"},"build_loadable_drivers")," OR ",(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_shared_drivers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," as a ",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started#the-shared-library-build"},(0,l.kt)("inlineCode",{parentName:"a"},"Shared"))," library.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," as a ",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started#the-static-build"},(0,l.kt)("inlineCode",{parentName:"a"},"Static"))," library archive.",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")," ",(0,l.kt)("inlineCode",{parentName:"td"},"qmake")," configuration option will be select by default when the ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG*=staticlib")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_tests")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build TinyORM unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_autoconf")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Disable the ",(0,l.kt)("a",{parentName:"td",href:"#auto-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Auto-configuration"))," feature ",(0,l.kt)("small",null,"(auto-configuration is enabled by default from ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"td"},"v0.34.0"),")"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_dotenv")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Disable the ",(0,l.kt)("a",{parentName:"td",href:"#environment-files"},(0,l.kt)("inlineCode",{parentName:"a"},"tiny_dotenv"))," feature ",(0,l.kt)("small",null,"(environment files are enabled by default from ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"td"},"v0.34.0"),")"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_thread_local")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Remove all ",(0,l.kt)("a",{parentName:"td",href:"https://en.cppreference.com/w/c/language/storage_duration"},(0,l.kt)("inlineCode",{parentName:"a"},"thread_local"))," storage duration specifiers, it disables multi-threading support.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_orm")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"enabled"),", then only the ",(0,l.kt)("inlineCode",{parentName:"td"},"query builder")," without ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM")," is compiled. Also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_tom")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"disabled"),", then it also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"extern_constants")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Use ",(0,l.kt)("inlineCode",{parentName:"td"},"extern")," constants instead of ",(0,l.kt)("inlineCode",{parentName:"td"},"inline")," constants in the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),".",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"ON")," is highly recommended for the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build")," ",(0,l.kt)("small",null,"(by default)"),";",(0,l.kt)("br",null),"is always ",(0,l.kt)("inlineCode",{parentName:"td"},"OFF")," for the ",(0,l.kt)("inlineCode",{parentName:"td"},"static build"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("code",null,"CONFIG(shared","|","dll):!inline_constants")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"inline_constants")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Use ",(0,l.kt)("inlineCode",{parentName:"td"},"inline")," constants instead of ",(0,l.kt)("inlineCode",{parentName:"td"},"extern")," constants in the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),".",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"OFF")," is highly recommended for the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),";",(0,l.kt)("br",null),"is always ",(0,l.kt)("inlineCode",{parentName:"td"},"ON")," for the ",(0,l.kt)("inlineCode",{parentName:"td"},"static build"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"link_pkgconfig_off")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Link against ",(0,l.kt)("inlineCode",{parentName:"td"},"mysqlclient")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"libmariadb")," with ",(0,l.kt)("inlineCode",{parentName:"td"},"PKGCONFIG"),".",(0,l.kt)("br",null),"Used only in the ",(0,l.kt)("inlineCode",{parentName:"td"},"Unix")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"MinGW")," ",(0,l.kt)("strong",{parentName:"td"},"shared")," build ",(0,l.kt)("small",null,"(exactly ",(0,l.kt)("code",null,"win32-g++","|","win32-clang-g++"),")")," and when ",(0,l.kt)("inlineCode",{parentName:"td"},"mysql_ping")," is also defined to link against ",(0,l.kt)("inlineCode",{parentName:"td"},"mysqlclient")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"libmariadb"),", ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L132"},"source code"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"unix:mysql_ping")," or ",(0,l.kt)("code",null,"(win32-g++","|","win32-clang-g++):mysql_ping:!static:!staticlib")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"mysql_ping")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::MySqlConnection::pingDatabase()")," method.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"tiny_ccache_win32")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable compiler cache. ",(0,l.kt)("a",{parentName:"td",href:"https://ccache.dev/"},"Homepage"),(0,l.kt)("br",null),(0,l.kt)("small",null,"It works only on Windows systems. It works well with the MSYS2 ",(0,l.kt)("inlineCode",{parentName:"td"},"g++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"clang++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc"),", and ",(0,l.kt)("inlineCode",{parentName:"td"},"clang-cl")," with ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc"),". It disables ",(0,l.kt)("inlineCode",{parentName:"td"},"precompile_header")," as they are not supported on Windows and changes the ",(0,l.kt)("inlineCode",{parentName:"td"},"-Zi")," compiler option to the ",(0,l.kt)("inlineCode",{parentName:"td"},"-Z7")," for debug builds as the ",(0,l.kt)("inlineCode",{parentName:"td"},"-Zi")," compiler option is not supported (",(0,l.kt)("a",{parentName:"td",href:"https://github.com/ccache/ccache/issues/1040"},"link")," to the issue)."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"tom_example")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build the ",(0,l.kt)("abbr",{title:"TinyORM Migrations"},(0,l.kt)("inlineCode",{parentName:"td"},"tom"))," console application example.")))))),(0,l.kt)("p",null,"Advanced ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ubsan")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Allows to enable ",(0,l.kt)("a",{parentName:"td",href:"https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html"},"UBSan")," sanitizer (Clang only).")))))),(0,l.kt)("p",null,"Important ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"th"},"CONFIG")," ",(0,l.kt)("small",null,"Option Name")),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ccache")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable compiler cache. ",(0,l.kt)("a",{parentName:"td",href:"https://ccache.dev/"},"Homepage"),(0,l.kt)("br",null),(0,l.kt)("small",null,"It works only on the Unix systems. It works well with the ",(0,l.kt)("inlineCode",{parentName:"td"},"g++")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"clang++")," and also supports precompiled headers."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"precompile_header")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable precompiled headers, you can disable them with:",(0,l.kt)("br",null)," ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG-=precompile_header"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"precompile_header")," is enabled by default on ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"g++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"clang++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"clang-cl")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"Windows")," and disabled by default on ",(0,l.kt)("inlineCode",{parentName:"td"},"linux"),"."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"static"),(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"staticlib")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build as a ",(0,l.kt)("inlineCode",{parentName:"td"},"static")," library (lib only).",(0,l.kt)("br",null),(0,l.kt)("small",null,"If you want to build all libraries in the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," project as static library archives and link against static libraries use the ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG += static"),". Don't use the ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG += staticlib"),".",(0,l.kt)("br",null),"See ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/NOTES.txt"},"NOTES.txt")," for more information (search ",(0,l.kt)("inlineCode",{parentName:"td"},"static vs staticlib"),")."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"static_runtime")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Link against the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared")," (dynamic) or ",(0,l.kt)("inlineCode",{parentName:"td"},"static")," run-time library.",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"-MD")," becomes ",(0,l.kt)("inlineCode",{parentName:"td"},"-MT")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"-MDd")," becomes ",(0,l.kt)("inlineCode",{parentName:"td"},"-MTd"),". It works only on ",(0,l.kt)("inlineCode",{parentName:"td"},"MSVC")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"MinGW")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"MSYS2"),".",(0,l.kt)("br",null),"Please ",(0,l.kt)("u",null,"don't use")," this option.",(0,l.kt)("br",null),"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"mingw")))))))),(0,l.kt)("h3",{id:"consume-tinyorm-library-qmake"},"Consume TinyOrm library ",(0,l.kt)("small",null,"(qmake)")),(0,l.kt)("p",null,"The ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/qmake/TinyOrm.pri"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyOrm.pri"))," file is available to simplify the integration of the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library into your application. It sets up and configures the ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"DEFINES")," qmake variables, adds the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM"),", ",(0,l.kt)("abbr",{title:"TinyORM Migrations"},(0,l.kt)("inlineCode",{parentName:"p"},"tom")),", and ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," header files on the system ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," (cross-platform using the ",(0,l.kt)("inlineCode",{parentName:"p"},"-isystem")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"-imsvc"),"), links against the TinyORM ",(0,l.kt)("inlineCode",{parentName:"p"},"shared")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"static")," library using the ",(0,l.kt)("inlineCode",{parentName:"p"},"LIBS"),"."),(0,l.kt)("p",null,"You can use it to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library when you are linking against it. It does a very similar thing like the CMake's ",(0,l.kt)("inlineCode",{parentName:"p"},"Find Modules")," feature."),(0,l.kt)("h4",{id:"requirements"},"Requirements"),(0,l.kt)("p",null,"It has a few requirements, you need to:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"specify path to the ",(0,l.kt)("inlineCode",{parentName:"li"},"TinyORM")," qmake features (",(0,l.kt)("inlineCode",{parentName:"li"},".prf")," files) using the ",(0,l.kt)("inlineCode",{parentName:"li"},"QMAKEFEATURES")," variable that can only be set in the ",(0,l.kt)("inlineCode",{parentName:"li"},".qmake.conf")," file"),(0,l.kt)("li",{parentName:"ul"},"specify ",(0,l.kt)("inlineCode",{parentName:"li"},"qmake")," or ",(0,l.kt)("inlineCode",{parentName:"li"},"environment")," variables to find the ",(0,l.kt)("inlineCode",{parentName:"li"},"vcpkg")," installation ",(0,l.kt)("small",null,"(",(0,l.kt)("inlineCode",{parentName:"li"},"TINY_VCPKG_ROOT")," and ",(0,l.kt)("inlineCode",{parentName:"li"},"TINY_VCPKG_TRIPLET"),")")),(0,l.kt)("li",{parentName:"ul"},"specify path to the ",(0,l.kt)("inlineCode",{parentName:"li"},"TinyORM")," build folder ",(0,l.kt)("small",null,"(",(0,l.kt)("inlineCode",{parentName:"li"},"TINYORM_BUILD_TREE"),")"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"you can specify it ",(0,l.kt)("strong",{parentName:"li"},"manually")),(0,l.kt)("li",{parentName:"ul"},"or you can use ",(0,l.kt)("a",{parentName:"li",href:"#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))))),(0,l.kt)("li",{parentName:"ul"},"build your application with the same ",(0,l.kt)("inlineCode",{parentName:"li"},"CONFIG")," ",(0,l.kt)("inlineCode",{parentName:"li"},"qmake")," variables that were used when building the ",(0,l.kt)("inlineCode",{parentName:"li"},"TinyORM")," library")),(0,l.kt)("p",null,"Let's explain one by one."),(0,l.kt)("h5",{id:"qmakefeatures"},(0,l.kt)("inlineCode",{parentName:"h5"},"QMAKEFEATURES")),(0,l.kt)("p",null,"Create the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file in your application root folder with the following content."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the PARENT folder of the TinyORM source folder\nTINY_MAIN_DIR = $$clean_path()\n# To find .env and .env.$$QMAKE_PLATFORM files in YOUR project\nTINY_DOTENV_ROOT = $$PWD\n\n# Path to the TinyORM build folder (specified manually)\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/)\n# vcpkg - range-v3 and tabulate\nTINY_VCPKG_ROOT = $$quote(/vcpkg/)\n#TINY_VCPKG_TRIPLET = x64-windows\n\n# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants\nQMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)\n")),(0,l.kt)("p",null,"You can move all ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variables that are part of the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration process to the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," file if you want (recommended), this is possible because the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," enables the ",(0,l.kt)("a",{parentName:"p",href:"#environment-files"},(0,l.kt)("inlineCode",{parentName:"a"},"Environment files"))," feature by default."),(0,l.kt)("p",null,"You can look at the ",(0,l.kt)("a",{parentName:"p",href:"/building/hello-world#auto-configure-using-qmake_conf-and-env"},"Auto-configure using .qmake.conf and .env")," example for ",(0,l.kt)("inlineCode",{parentName:"p"},"Hello world")," project of what must stay in the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake.conf")," file and what can be moved to the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can use the ",(0,l.kt)("a",{parentName:"p",href:"#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," if you don't like to specify it manually.")),(0,l.kt)("h5",{id:"variables-affecting-tinyormpri"},"Variables affecting ",(0,l.kt)("inlineCode",{parentName:"h5"},"TinyOrm.pri")),(0,l.kt)("p",null,"You must define the following variables before the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," is included:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_BUILD_TREE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," build folder.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_ROOT")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," installation folder.",(0,l.kt)("br",null),"If not defined, then it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_ROOT")," environment variable.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_TRIPLET")),(0,l.kt)("td",{parentName:"tr",align:null},"The ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," to use ",(0,l.kt)("small",null,"(vcpkg/installed/$$TINY_VCPKG_TRIPLET/)"),".",(0,l.kt)("br",null),"If not defined, then it tries to guess the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," based on the current compiler and OS (based on the ",(0,l.kt)("inlineCode",{parentName:"td"},"QMAKESPEC"),"), and as the last thing, it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_DEFAULT_TRIPLET")," environment variable.")))),(0,l.kt)("p",null,"These variables will be set after the configuration is done:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_BUILD_SUBFOLDER")),(0,l.kt)("td",{parentName:"tr",align:null},"Folder by release type if ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG+=debug_and_release")," is defined ",(0,l.kt)("small",null,"(/debug, /release, or an empty string)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_CCACHE_BUILD")),(0,l.kt)("td",{parentName:"tr",align:null},"To correctly link ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache")," build against a ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache")," build ",(0,l.kt)("small",null,"(_ccache or an empty string)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MSVC_VERSION")),(0,l.kt)("td",{parentName:"tr",align:null},"The ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc")," compiler string ",(0,l.kt)("small",null,"(MSVC2022 or MSVC2019)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_QT_VERSION_UNDERSCORED")),(0,l.kt)("td",{parentName:"tr",align:null},"Underscored ",(0,l.kt)("inlineCode",{parentName:"td"},"Qt")," version ",(0,l.kt)("small",null,"(eg. 6_7_0)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_RELEASE_TYPE_CAMEL")),(0,l.kt)("td",{parentName:"tr",align:null},"Build type string ",(0,l.kt)("small",null,"(Debug, Profile, or Release)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_INCLUDE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"include")," folder ",(0,l.kt)("small",null,"(vcpkg/installed/","<","triplet",">","/include/)"),".")))),(0,l.kt)("p",null,"Then you simply include the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," in your project file."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='AnyProject.pro'",title:"'AnyProject.pro'"},"include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n")),(0,l.kt)("p",null,"And that is all, now you should be able to link against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. \ud83d\udc4c"),(0,l.kt)("h5",{id:"manual-configuration-examples"},"Manual configuration examples"),(0,l.kt)("p",null,"Frankly, there is no reason to use the Manual configuration (define the variables described below before the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," inclusion), the only reason to use it is when you want more control over this process or want to define everything yourself. I'll leave this section here to show how things work."),(0,l.kt)("p",null,"You will have to link against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library manually if you don't set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variable before the inclusion of the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," file. The ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," is auto-detected every time."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"{9}","{9}":!0},"# Link against TinyORM library\n# ---\nTINY_MAIN_DIR = $$clean_path()\n\n# Configure TinyORM library\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n\n# TinyORM library path\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake)\nLIBS += $$quote(-L$$TINYORM_BUILD_TREE/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/src$${TINY_BUILD_SUBFOLDER}/)\nLIBS += -lTinyOrm\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"{9}","{9}":!0},"# Link against TinyORM library\n# ---\nTINY_MAIN_DIR = $$clean_path()\n\n# Configure TinyORM library\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n\n# TinyORM library path\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake)\nLIBS += $$quote(-L$$TINYORM_BUILD_TREE/build-TinyORM-Desktop_Qt_6_7_0_GCC_64bit-Debug/src$${TINY_BUILD_SUBFOLDER}/)\nLIBS += -lTinyOrm\n")))),(0,l.kt)("p",null,"The same is true for the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," include path. If you don't set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_VCPKG_ROOT")," or have not defined the ",(0,l.kt)("inlineCode",{parentName:"p"},"VCPKG_ROOT")," environment variable, then you need to set up the ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," for the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," that provides the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," header files."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# vcpkg - range-v3 and tabulate\n# ---\nINCLUDEPATH += $$quote(/vcpkg/installed/x64-windows/include/)\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# vcpkg - range-v3 and tabulate\n# ---\nQMAKE_CXXFLAGS += -isystem $$shell_quote(/vcpkg/installed/x64-linux/include/)\n")))),(0,l.kt)("p",null,"You can also use TinyORM's ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," function ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_add_system_includepath()")," which handles ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," in a cross-platform way."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# vcpkg - range-v3 and tabulate\n# ---\nload(tiny_system_includepath)\ntiny_add_system_includepath(/vcpkg/installed/x64-linux/include/)\n")),(0,l.kt)("p",null,"Do not forget to add ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm0.dll")," on the path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so your application can find it during execution."),(0,l.kt)(p.Z,{groupId:y.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,k.go)(y.Fo,!1)}\\TinyORM\\TinyORM-builds-qmake\\build-debug;" + $env:Path`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,k.go)(y.q5)}/TinyORM/TinyORM-builds-qmake/build-debug\${PATH:+:}$PATH`))),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"On Linux ",(0,l.kt)("inlineCode",{parentName:"p"},"-isystem")," marks the directory as a system directory, it prevents warnings."),(0,l.kt)("p",{parentName:"admonition"},"On Windows you can use ",(0,l.kt)("inlineCode",{parentName:"p"},"QMAKE_CXXFLAGS_WARN_ON = -external:anglebrackets -external:W0"),", it applies a warning level 0 to the angel bracket includes; ",(0,l.kt)("inlineCode",{parentName:"p"},"#include "),"."),(0,l.kt)("p",{parentName:"admonition"},"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"clang-cl")," with ",(0,l.kt)("inlineCode",{parentName:"p"},"MSVC")," you can use ",(0,l.kt)("inlineCode",{parentName:"p"},"-imsvc"),".")),(0,l.kt)("h3",{id:"auto-configuration-internals"},"Auto-configuration internals"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system does not support ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-configuration")," of dependencies out of the box but ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," from ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0")," added its own ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature along with the ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," qmake feature. These new features allow us to ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-configure")," ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project, and with their help, the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files can be ",(0,l.kt)("u",null,"skipped entirely"),"."),(0,l.kt)("p",null,"While it adds additional complexity to the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration process, the benefits are significant."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature is designed to find the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"MySQL")," installations, and ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," to include the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," and ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)")," files in the project's root folder. These new features can be configured using ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"environment")," variables, and they also contain some guessing logic if these variables are not defined."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_autoconf"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_autoconf"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_autoconf"),")."),(0,l.kt)("p",null,"These are ",(0,l.kt)("u",null,(0,l.kt)("inlineCode",{parentName:"p"},"qmake"))," and ",(0,l.kt)("u",null,(0,l.kt)("inlineCode",{parentName:"p"},"environment"))," variables that affect the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_ROOT")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," installation folder.",(0,l.kt)("br",null),"If not defined, then it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_ROOT")," environment variable.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_TRIPLET")),(0,l.kt)("td",{parentName:"tr",align:null},"The ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," to use ",(0,l.kt)("small",null,"(vcpkg/installed/$$TINY_VCPKG_TRIPLET/)"),".",(0,l.kt)("br",null),"If not defined, then it tries to guess the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," based on the current compiler and OS (based on the ",(0,l.kt)("inlineCode",{parentName:"td"},"QMAKESPEC"),"), and as the last thing, it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_DEFAULT_TRIPLET")," environment variable.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MYSQL_ROOT")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," installation folder.",(0,l.kt)("br",null),"If not defined, then it tries to guess the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," installation folder (",(0,l.kt)("inlineCode",{parentName:"td"},"win32")," only): ",(0,l.kt)("code",null,"$$(ProgramFiles)/MySQL/MySQL Server (8.3","|","8.2","|","8.1","|","8.0","|","5.7)/"))))),(0,l.kt)("p",null,"You can set these variables in the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," (recommended) or ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files, in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file (or wherever you want), or as environment variables."),(0,l.kt)("p",null,"These variables will be set after ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-configuration")," is done:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_INCLUDE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"include")," folder ",(0,l.kt)("small",null,"(vcpkg/installed/","<","triplet",">","/include/)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MYSQL_INCLUDE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," ",(0,l.kt)("inlineCode",{parentName:"td"},"include")," folder ",(0,l.kt)("small",null,"(MySQL Server 8.3/include/)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MYSQL_LIB")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," ",(0,l.kt)("inlineCode",{parentName:"td"},"lib")," folder ",(0,l.kt)("small",null,"(MySQL Server 8.3/lib/)"),".")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_MYSQL_INCLUDE")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_MYSQL_LIB")," are only set on ",(0,l.kt)("inlineCode",{parentName:"p"},"win32")," platform except ",(0,l.kt)("inlineCode",{parentName:"p"},"mingw"),"."),(0,l.kt)("h4",{id:"environment-files"},"Environment files"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature allows us to define the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," and ",(0,l.kt)("inlineCode",{parentName:"p"},".env.$$TINY_DOTENV_PLATFORM")," files in the project's root folder. These files are loaded as early as possible so you can affect the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration process. On the other hand, the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are loaded as late as possible, and they can be used to override the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," file is included ",(0,l.kt)("u",null,"first")," and is included on all platforms."),(0,l.kt)("p",null,"There is only one requirement for this feature to work correctly, and that is to set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_DOTENV_ROOT")," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variable to the project's root folder. This variable is ",(0,l.kt)("strong",{parentName:"p"},"already")," set in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file for the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project."),(0,l.kt)("p",null,"Then the following names are taken into account: .env, .env.win32, .env.unix, .env.mingw"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# To find .env and .env.$$QMAKE_PLATFORM files\nTINY_DOTENV_ROOT = $$PWD\n")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_dotenv"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_dotenv"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_dotenv"),")."),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},(0,l.kt)("inlineCode",{parentName:"p"},"Environment files")," don't work in the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," builds.")),(0,l.kt)("h4",{id:"partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"h4"},"TINYORM_BUILD_TREE")),(0,l.kt)("p",null,"You don't have to manually define the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," in ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," or ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," files. The ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," absolute path can be put together for you (this is happening inside the ",(0,l.kt)("inlineCode",{parentName:"p"},"variables.pri")," file) and ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build folder name can be guessed for you too."),(0,l.kt)("p",null,"You must define the following variables before the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," will be included to make this real (set them in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf"),"):"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MAIN_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("strong",{parentName:"td"},"PARENT")," folder of the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," source folder.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_BUILD_TREE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("strong",{parentName:"td"},"current")," build tree - ",(0,l.kt)("inlineCode",{parentName:"td"},"TINY_BUILD_TREE = $$shadowed($$PWD)"),".")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_MAIN_DIR")," is required for another features anyway (so it should already be set) and all that's left is to set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_BUILD_TREE"),"."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the current build tree (used to guess the TinyORM build tree)\nTINY_BUILD_TREE = $$shadowed($$PWD)\n")),(0,l.kt)("p",null,"If you will follow this pattern or logic then you can switch ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator Kits")," and the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," will be ",(0,l.kt)("strong",{parentName:"p"},"auto-generated")," correctly and will always point to the correct ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build tree."),(0,l.kt)("p",null,"It works this way, all is happening inside the ",(0,l.kt)("inlineCode",{parentName:"p"},"variables.pri"),", it takes a build folder name for the ",(0,l.kt)("strong",{parentName:"p"},"current")," project eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"build-HelloWorld-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug"),", replaces the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," with the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," and as we already know the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build folder location we can simply concatenate these paths like ",(0,l.kt)("inlineCode",{parentName:"p"},"$$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug"),"."),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"This will only work if you follow the recommended ",(0,l.kt)("a",{parentName:"p",href:"#folders-structure"},(0,l.kt)("inlineCode",{parentName:"a"},"Folders structure")),".")),(0,l.kt)("h3",{id:"manual-configuration-internals"},"Manual configuration internals"),(0,l.kt)("p",null,"There is not much to say about the ",(0,l.kt)("inlineCode",{parentName:"p"},"Manual configuration")," feature. It uses ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files (there are four, one for every project or sub-project), and every project has prepared its own ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri.example")," file for faster initial configuration."),(0,l.kt)("p",null,"These ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri.example")," files are nicely commented on, so you can see what needs to be modified. The ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are loaded as late as possible, and they can be used to override the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration."),(0,l.kt)("p",null,"If the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature is disabled and there are no ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files, then the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration or build will fail at 100%."),(0,l.kt)("p",null,"These ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are intended for configuring qmake's ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"LIBS"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG")," or eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"QMAKE_LFLAGS"),", or any other ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," options or variables."),(0,l.kt)("h2",{id:"ccache-support"},"Ccache support"),(0,l.kt)("p",null,"The TinyORM supports the ",(0,l.kt)("a",{parentName:"p",href:"https://ccache.dev/"},(0,l.kt)("inlineCode",{parentName:"a"},"ccache"))," out of the box for all ",(0,l.kt)("a",{parentName:"p",href:"/supported-compilers"},"supported compilers"),". For qmake you can enable it using the ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG+=ccache")," on Linux or ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG+=tiny_ccache_win32")," on Windows. For CMake you can set the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_CXX_COMPILER_LAUNCHER=ccache"),"."),(0,l.kt)("p",null,"On ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux")," it's clear, the ccache is fully supported and works also with the ",(0,l.kt)("inlineCode",{parentName:"p"},"precompiled headers"),". But was necessary to add some workarounds to the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake"),"/",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," build systems to make out of the box support on ",(0,l.kt)("inlineCode",{parentName:"p"},"Windows"),". When you enable the ",(0,l.kt)("inlineCode",{parentName:"p"},"ccache")," on ",(0,l.kt)("inlineCode",{parentName:"p"},"Windows")," then the build system disables ",(0,l.kt)("inlineCode",{parentName:"p"},"precompiled headers")," and replaces the ",(0,l.kt)("inlineCode",{parentName:"p"},"-Zi")," compiler option with the ",(0,l.kt)("inlineCode",{parentName:"p"},"-Z7")," (link to the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/ccache/ccache/issues/1040"},"issue"),")."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can install the ccache using the ",(0,l.kt)("inlineCode",{parentName:"p"},"scoop install ccache")," command on Windows.")))}R.isMDXComponent=!0},5705:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-additional_arguments-14d3b6b82ad6d28db5b999a462500a6a.png"},7066:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-build_settings-7caa6d7c86232484b82acb24b5a3a6a7.png"},6874:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-configure_project-0b6821ea0523567dab9f21b3215055a3.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[969],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),i=n(6010);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,i.Z)(l.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>f});var a=n(7462),i=n(7294),l=n(6010),r=n(2466),o=n(6550),d=n(1980),p=n(7392),m=n(12);function s(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:i}}=e;return{value:t,label:n,attributes:a,default:i}}))}function k(e){const{values:t,children:n}=e;return(0,i.useMemo)((()=>{const e=t??s(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function u(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function N(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.k6)(),l=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,d._X)(l),(0,i.useCallback)((e=>{if(!l)return;const t=new URLSearchParams(a.location.search);t.set(l,e),a.replace({...a.location,search:t.toString()})}),[l,a])]}function c(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,l=k(e),[r,o]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!u({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:l}))),[d,p]=N({queryString:n,groupId:a}),[s,c]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,m.Nk)(n);return[a,(0,i.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),h=(()=>{const e=d??s;return u({value:e,tabValues:l})?e:null})();(0,i.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!u({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),c(e)}),[p,c,l]),tabValues:l}}var h=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:d,tabValues:p}=e;const m=[],{blockElementScrollPositionUntilNextRender:s}=(0,r.o5)(),k=e=>{const t=e.currentTarget,n=m.indexOf(t),a=p[n].value;a!==o&&(s(t),d(a))},u=e=>{let t=null;switch(e.key){case"Enter":k(e);break;case"ArrowRight":{const n=m.indexOf(e.currentTarget)+1;t=m[n]??m[0];break}case"ArrowLeft":{const n=m.indexOf(e.currentTarget)-1;t=m[n]??m[m.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:r}=e;return i.createElement("li",(0,a.Z)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>m.push(e),onKeyDown:u,onClick:k},r,{className:(0,l.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":o===t})}),n??t)})))}function C(e){let{lazy:t,children:n,selectedValue:a}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=l.find((e=>e.props.value===a));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},l.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function y(e){const t=c(e);return i.createElement("div",{className:(0,l.Z)("tabs-container",b.tabList)},i.createElement(g,(0,a.Z)({},e,t)),i.createElement(C,(0,a.Z)({},e,t)))}function f(e){const t=(0,h.Z)();return i.createElement(y,(0,a.Z)({key:String(t)},e))}},5178:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),i=n(6550);const l={apiTable:"apiTable_flxF"};const r=(0,a.forwardRef)(((e,t)=>{let{name:n,children:l}=e;const r=function(e){let t=e;for(;(0,a.isValidElement)(t);)[t]=a.Children.toArray(t.props.children);return t}(l),o=n?`#${n}-${r}`:`#${r}`,d=(0,i.k6)();return a.createElement("tr",{id:r,tabIndex:0,ref:d.location.hash===o?t:void 0,onClick:()=>{d.push(o)},onKeyDown:e=>{"Enter"===e.key&&d.push(o)}},l.props.children)}));function o(e){let{children:t,name:n}=e;const[i,o]=a.Children.toArray(t.props.children),d=(0,a.useRef)(null);(0,a.useEffect)((()=>{d.current?.focus()}),[d]);const p=a.Children.map(o.props.children,(e=>a.createElement(r,{name:n,ref:d},e)));return a.createElement("table",{className:l.apiTable},i,a.createElement("tbody",null,p))}},2044:(e,t,n)=>{n.d(t,{$t:()=>s,Ae:()=>h,C:()=>N,DK:()=>b,Fo:()=>o,Fs:()=>i,IM:()=>c,IZ:()=>a,RS:()=>_,VE:()=>g,Wg:()=>y,_A:()=>p,al:()=>T,jk:()=>u,js:()=>d,of:()=>m,q5:()=>r,qb:()=>f,vk:()=>k,wU:()=>l,zg:()=>C});const a="shell",i="database",l="application",r="bash",o="pwsh",d="zsh",p="maria",m="mysql",s="postgres",k="sqlite",u="application",N="bash",c="pwsh",h="zsh",b="MariaDB",g="MySQL",C="PostgreSQL",y="SQLite",f="tinyorm.org",T="$HOME/Code/c/",_="$env:USERPROFILE\\Code\\c\\"},4355:(e,t,n)=>{n.d(t,{Z:()=>l});var a=n(7294),i=n(9482);function l(){const e=(0,a.useContext)(i.Z);if(null!=e)return e;throw new Error("useRootFolderContext is used outside of Layout component.")}},6005:(e,t,n)=>{n.d(t,{AE:()=>o,EA:()=>r,em:()=>p,go:()=>d,mT:()=>m,we:()=>s});var a=n(4355),i=n(2389),l=n(2044);const r=function(e,t){return void 0===t&&(t=!0),k((0,a.Z)().rootFolder[e]??p(e),e,t)},o=()=>(0,a.Z)().rootFolder[l.wU]??p(l.wU),d=function(e,t){if(void 0===t&&(t=!0),null==e)throw new Error("The groupId in the applicationFolderPath() can not be empty.");const n=t||e!==l.Fo?"/":"\\";return k(r(e)+n+o(),e,t)};function p(e){if(null==e)throw new Error("The groupId in the folderDefaultValue() can not be empty.");if(!(0,i.Z)())return"";switch(e){case l.Fo:return l.RS;case l.q5:return l.al;case l.wU:return l.qb;default:throw new Error(`No default value for '${e}' groupId in the folderDefaultValue().`)}}function m(e){return e===l.wU}function s(e,t){if(null==t||""===t)return t;const n="$ENV{$1}$2";switch(e){case l.Fo:return N(t).replace(/\$env:(.+?)(\/.*)/,n);case l.q5:return t.replace(/\$(.+?)(\/.*)/,n);default:throw new Error(`Unsupported shell type '${e}' in the convertToCmakeEnvVariable().`)}}function k(e,t,n){if(void 0===n&&(n=!0),null==e||""===e)return e;if(t!==l.Fo)return u(e);const a=u(e);return n?N(a):function(e){return null==e||""===e?e:e.replaceAll(/\/+/g,"\\")}(a)}function u(e){return null==e||""===e?e:e.replace(/[/\\]+$/,"")}function N(e){return null==e||""===e?e:e.replaceAll(/\\+(?! )/g,"/")}},4040:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>v,contentTitle:()=>T,default:()=>R,frontMatter:()=>f,metadata:()=>_,toc:()=>O});var a=n(7462),i=n(7294),l=n(3905),r=n(5178),o=n(7693),d=n(5162),p=n(4866),m=n(5697),s=n.n(m),k=n(6005);function u(e){let{groupId:t}=e;return i.createElement("span",null,(0,k.go)(t))}u.propTypes={groupId:s().string.isRequired};const N=u;var c=n(6010),h=n(4355);const b={rootFolderInput:"rootFolderInput_ottS",input:"input_OR7e",application:"application_fjej"};function g(e){let{groupId:t,label:n}=e;const{rootFolder:a,setRootFolder:l}=(0,h.Z)(),r=(0,k.mT)(t),o=r?"application":"root",d=r?"\nThis folder name is common for all shells (eg. pwsh, bash, ...)":"";return i.createElement("form",{name:"tinyorm-root-folder-form",className:(0,c.Z)(b.rootFolderInput,b[t],t),onSubmit:e=>{e.preventDefault(),e.stopPropagation()}},i.createElement("input",{name:"tinyorm-root-folder-input",className:(0,c.Z)(b.input,b[t],t),placeholder:`Enter ${o} folder...`,title:`This ${o} folder will be used in all ${n} examples at tinyorm.org${d}`,onChange:e=>{l(t,e.target.value)},value:a[t]??(0,k.em)(t)}))}g.propTypes={groupId:s().string.isRequired,label:s().string.isRequired};const C=g;var y=n(2044);const f={sidebar_position:0,sidebar_label:"TinyORM",hide_table_of_contents:!0,description:"How to compile the TinyORM C++ library on Windows and Linux.",keywords:["c++ orm","building","tinyorm"]},T="Building: TinyORM",_={unversionedId:"building/tinyorm",id:"building/tinyorm",title:"Building: TinyORM",description:"How to compile the TinyORM C++ library on Windows and Linux.",source:"@site/docs/building/tinyorm.mdx",sourceDirName:"building",slug:"/building/tinyorm",permalink:"/building/tinyorm",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/building/tinyorm.mdx",tags:[],version:"current",sidebarPosition:0,frontMatter:{sidebar_position:0,sidebar_label:"TinyORM",hide_table_of_contents:!0,description:"How to compile the TinyORM C++ library on Windows and Linux.",keywords:["c++ orm","building","tinyorm"]},sidebar:"tinyormSidebar",previous:{title:"Getting Started",permalink:"/tinydrivers/getting-started"},next:{title:"Hello world",permalink:"/building/hello-world"}},v={},O=[{value:"Introduction",id:"introduction",level:2},{value:"Common Prerequisites",id:"common-prerequisites",level:4},{value:"Windows Prerequisites",id:"windows-prerequisites",level:4},{value:"Build environment scripts",id:"build-environment-scripts",level:5},{value:"Allow symbolic links unprivileged",id:"allow-symbolic-links-unprivileged",level:5},{value:"Folders structure",id:"folders-structure",level:2},{value:"Getting started",id:"getting-started",level:2},{value:"vcpkg",id:"vcpkg",level:2},{value:"Set up vcpkg environment",id:"set-up-vcpkg-environment",level:4},{value:"C preprocessor macros",id:"c-preprocessor-macros",level:2},{value:"Building with CMake",id:"building-with-cmake",level:2},{value:"Configure & Build (cmake)",id:"configure-and-build-cmake",level:3},{value:"CMake STRICT_MODE option",id:"cmake-strict_mode-option",level:5},{value:"Build TinyORM",id:"build-tinyorm",level:4},{value:"CMake build options",id:"cmake-build-options",level:3},{value:"Consume TinyOrm library (cmake)",id:"consume-tinyorm-library-cmake",level:3},{value:"Building with qmake",id:"building-with-qmake",level:2},{value:"Install dependencies",id:"install-dependencies",level:3},{value:"Configure & Build (qmake)",id:"configure-and-build-qmake",level:3},{value:"Open QtCreator IDE",id:"open-qtcreator-ide",level:4},{value:"Configure TinyORM",id:"configure-tinyorm",level:4},{value:"Auto-configuration and tiny_dotenv",id:"auto-configuration-and-tiny_dotenv",level:5},{value:"Manual configuration (conf.pri)",id:"manual-configuration-confpri",level:5},{value:"Opening TinyORM.pro (main project file)",id:"opening-tinyormpro-main-project-file",level:5},{value:"Build TinyORM",id:"build-tinyorm-1",level:4},{value:"qmake build options",id:"qmake-build-options",level:3},{value:"Consume TinyOrm library (qmake)",id:"consume-tinyorm-library-qmake",level:3},{value:"Requirements",id:"requirements",level:4},{value:"QMAKEFEATURES",id:"qmakefeatures",level:5},{value:"Variables affecting TinyOrm.pri",id:"variables-affecting-tinyormpri",level:5},{value:"Manual configuration examples",id:"manual-configuration-examples",level:5},{value:"Auto-configuration internals",id:"auto-configuration-internals",level:3},{value:"Environment files",id:"environment-files",level:4},{value:"Partial guessing of the TINYORM_BUILD_TREE",id:"partial-guessing-of-the-tinyorm_build_tree",level:4},{value:"Manual configuration internals",id:"manual-configuration-internals",level:3},{value:"Ccache support",id:"ccache-support",level:2}],I={toc:O},M="wrapper";function R(e){let{components:t,...i}=e;return(0,l.kt)(M,(0,a.Z)({},I,i,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("h1",{id:"building-tinyorm"},"Building: TinyORM"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#introduction"},"Introduction"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#common-prerequisites"},"Common Prerequisites")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#windows-prerequisites"},"Windows Prerequisites")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#folders-structure"},"Folders structure")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#getting-started"},"Getting started")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#vcpkg"},"vcpkg")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#c-preprocessor-macros"},"C preprocessor macros")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#building-with-cmake"},"Building with CMake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#configure-and-build-cmake"},"Configure & Build")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#cmake-build-options"},"CMake build options")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#consume-tinyorm-library-cmake"},"Consume TinyOrm library")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#building-with-qmake"},"Building with qmake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#install-dependencies"},"Install dependencies")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#configure-and-build-qmake"},"Configure & Build")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#qmake-build-options"},"qmake build options")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#consume-tinyorm-library-qmake"},"Consume TinyOrm library")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#auto-configuration-internals"},"Auto-configuration internals"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#environment-files"},"Environment files")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#manual-configuration-internals"},"Manual configuration internals")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#ccache-support"},"Ccache support"))),(0,l.kt)("h2",{id:"introduction"},"Introduction"),(0,l.kt)("p",null,"The build systems supported out of the box are ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake"),"."),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"All examples below assume that ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh")," runs on ",(0,l.kt)("inlineCode",{parentName:"p"},"Windows")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"bash")," runs on ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux"),".")),(0,l.kt)("h4",{id:"common-prerequisites"},"Common Prerequisites"),(0,l.kt)("p",null,"Install the required ",(0,l.kt)("a",{parentName:"p",href:"/dependencies"},"dependencies")," before starting."),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"QSqlDatabase")," depends on ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," from ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt v6.5.3")," so you must create the ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," instance before you will call anything from the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. \ud83e\udee4 The change was made ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/qt/qtbase/commit/8d2bdc9cd5482eace12ba7e45304857bd24db0e6#diff-1d355c25c0b0eddec2be48253407780c4dc510d986739aec61e1ec892ccaf86e"},"here"),".")),(0,l.kt)("h4",{id:"windows-prerequisites"},"Windows Prerequisites"),(0,l.kt)("h5",{id:"build-environment-scripts"},"Build environment scripts"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Visual Studio")," does not provide ",(0,l.kt)("inlineCode",{parentName:"p"},"vcvars")," scripts for ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh"),", you can use ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/tools/vcvars64.ps1"},(0,l.kt)("inlineCode",{parentName:"a"},"vcvars64.ps1"))," provided by ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," in the ",(0,l.kt)("inlineCode",{parentName:"p"},"tools/")," folder. Place them on the ",(0,l.kt)("inlineCode",{parentName:"p"},"$env:Path")," user/system path and they will be available system-wide."),(0,l.kt)("p",null,"The same is true for the ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt Framework"),", it doesn't provide ",(0,l.kt)("inlineCode",{parentName:"p"},"qtenv")," scripts for ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh")," too. You can create your own script, place it on the ",(0,l.kt)("inlineCode",{parentName:"p"},"$env:Path")," user/system path and it will be available system-wide."),(0,l.kt)("p",null,"Here is one simple example for ",(0,l.kt)("inlineCode",{parentName:"p"},"pwsh"),"."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:"qtenv6.ps1",label:"qtenv6.ps1",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},"Write-Host 'Setting up environment for Qt 6.7.0 usage...' -ForegroundColor Magenta\n$env:Path = 'C:\\Qt\\6.7.0\\msvc2019_64\\bin;' + $env:Path\n. E:\\dotfiles\\bin\\vcvars64.ps1\n"))),(0,l.kt)(d.Z,{value:"qtenv5.ps1",label:"qtenv5.ps1",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},"Write-Host 'Setting up environment for Qt 5.15.2 usage...' -ForegroundColor Magenta\n$env:Path = 'C:\\Qt\\5.15.2\\msvc2019_64\\bin;' + $env:Path\n. E:\\dotfiles\\bin\\vcvars64.ps1\n")))),(0,l.kt)("p",null,"And here for ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux"),"."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:"qtenv6",label:"qtenv6",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"echo 'Setting up environment for Qt 6.7.0 usage...'\n\nexport PATH=/opt/Qt/6.7.0/gcc_64/bin${PATH:+:}$PATH\nexport LD_LIBRARY_PATH=/opt/Qt/6.7.0/gcc_64/lib${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH\n"))),(0,l.kt)(d.Z,{value:"qtenv5",label:"qtenv5",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"echo 'Setting up environment for Qt 5.15.2 usage...'\n\nexport PATH=/opt/Qt/5.15.2/gcc_64/bin${PATH:+:}$PATH\nexport LD_LIBRARY_PATH=/opt/Qt/5.15.2/gcc_64/lib${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH\n")))),(0,l.kt)("h5",{id:"allow-symbolic-links-unprivileged"},"Allow symbolic links unprivileged"),(0,l.kt)("p",null,"Open ",(0,l.kt)("inlineCode",{parentName:"p"},"Local Security Policy"),", go to ",(0,l.kt)("inlineCode",{parentName:"p"},"Local Policies - User Rights Assignment"),", open ",(0,l.kt)("inlineCode",{parentName:"p"},"Create symbolic links")," and add your user account or user group, restart when it doesn't apply immediately."),(0,l.kt)("h2",{id:"folders-structure"},"Folders structure"),(0,l.kt)("p",null,"All ",(0,l.kt)("inlineCode",{parentName:"p"},"tinyorm.org")," examples are based on the following folders structure. The ",(0,l.kt)("inlineCode",{parentName:"p"},"tom")," folder will contain a ",(0,l.kt)("a",{parentName:"p",href:"/building/migrations"},"migrations console application"),"."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can set the root and application folder paths in the form below and they will be used across the whole ",(0,l.kt)("a",{parentName:"p",href:"http://www.tinyorm.org"},"www.tinyorm.org")," website. \ud83e\udd73 The pwsh shell is supposed to use on Windows and the bash shell on Linux, but it is not a requirement.")),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,className:"tiny-tree",mdxType:"TabItem"},(0,l.kt)("div",{className:"tiny-root-folder-info-wrapper"},(0,l.kt)("span",{className:"tiny-root-folder-info-prefix"},"Current pwsh path"),"\xa0",(0,l.kt)(N,{groupId:y.Fo,mdxType:"RootFolder"})),(0,l.kt)(C,{groupId:y.Fo,label:y.IM,mdxType:"RootFolderInput"}),(0,l.kt)(C,{groupId:y.wU,label:y.jk,mdxType:"RootFolderInput"}),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-text"},"\n\n\n\u251c\u2500\u2500\n\u2502 \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld-builds-cmake/\n\u2502 | | \u2514\u2500\u2500 build-debug/\n\u2502 | \u2514\u2500\u2500 HelloWorld-builds-qmake/\n\u2502 | \u2514\u2500\u2500 build-debug/\n\u2502 \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM-builds-cmake/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-debug/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-release/\n\u2502 | \u2502 \u2514\u2500\u2500 build-clang-debug/\n\u2502 | \u2514\u2500\u2500 TinyORM-builds-qmake/\n\u2502 | \u251c\u2500\u2500 build-debug/\n\u2502 | \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug/\n\u2502 | \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_MSYS2_UCRT64_64bit-Release/\n\u2502 \u2514\u2500\u2500 tom/\n\u2502 \u251c\u2500\u2500 tom/\n\u2502 \u2502 \u2514\u2500\u2500 database/\n\u2502 \u2502 \u251c\u2500\u2500 migrations/\n\u2502 \u2502 \u251c\u2500\u2500 seeders/\n\u2502 \u2502 \u251c\u2500\u2500 migrations.pri\n\u2502 \u2502 \u2514\u2500\u2500 seeders.pri\n\u2502 \u251c\u2500\u2500 tom-builds-cmake/\n\u2502 \u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/\n\u2502 \u2514\u2500\u2500 tom-builds-qmake/\n\u2502 \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_3_MSYS2_UCRT64_64bit-Release/\n\u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/\n\u251c\u2500\u2500 tmp/\n\u2514\u2500\u2500 vcpkg/\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,className:"tiny-tree",mdxType:"TabItem"},(0,l.kt)("div",{className:"tiny-root-folder-info-wrapper"},(0,l.kt)("span",{className:"tiny-root-folder-info-prefix"},"Current bash path"),"\xa0",(0,l.kt)(N,{groupId:y.q5,mdxType:"RootFolder"})),(0,l.kt)(C,{groupId:y.q5,label:y.C,mdxType:"RootFolderInput"}),(0,l.kt)(C,{groupId:y.wU,label:y.wU,mdxType:"RootFolderInput"}),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-text"},"\n\n\n\u251c\u2500\u2500\n\u2502 \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld/\n\u2502 | \u251c\u2500\u2500 HelloWorld-builds-cmake/\n\u2502 | | \u2514\u2500\u2500 build-debug/\n\u2502 | \u2514\u2500\u2500 HelloWorld-builds-qmake/\n\u2502 | \u2514\u2500\u2500 build-debug/\n\u2502 \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM/\n\u2502 | \u251c\u2500\u2500 TinyORM-builds-cmake/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-debug/\n\u2502 | \u2502 \u251c\u2500\u2500 build-gcc-release/\n\u2502 | \u2502 \u2514\u2500\u2500 build-clang-debug/\n\u2502 | \u2514\u2500\u2500 TinyORM-builds-qmake/\n\u2502 | \u251c\u2500\u2500 build-debug/\n\u2502 | \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_GCC_64bit-Debug/\n\u2502 | \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_5_15_2_clang13_64bit_ccache-Release/\n\u2502 \u2514\u2500\u2500 tom/\n\u2502 \u251c\u2500\u2500 tom/\n\u2502 \u2502 \u2514\u2500\u2500 database/\n\u2502 \u2502 \u251c\u2500\u2500 migrations/\n\u2502 \u2502 \u251c\u2500\u2500 seeders/\n\u2502 \u2502 \u251c\u2500\u2500 migrations.pri\n\u2502 \u2502 \u2514\u2500\u2500 seeders.pri\n\u2502 \u251c\u2500\u2500 tom-builds-cmake/\n\u2502 \u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_clang14_64bit_ccache-Debug/\n\u2502 \u2514\u2500\u2500 tom-builds-qmake/\n\u2502 \u251c\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_GCC_64bit-Debug/\n\u2502 \u2514\u2500\u2500 build-TinyORM-Desktop_Qt_6_7_0_clang14_64bit_ccache-Release/\n\u251c\u2500\u2500 tmp/\n\u2514\u2500\u2500 vcpkg/\n")))),(0,l.kt)("admonition",{type:"danger"},(0,l.kt)("p",{parentName:"admonition"},"Avoid paths with spaces with the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system, it will not compile.")),(0,l.kt)("a",{id:"qtcreator-default-build-directory"}),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can force the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described above."),(0,l.kt)("p",{parentName:"admonition"},"To generate the required folders structure set the ",(0,l.kt)("inlineCode",{parentName:"p"},"Settings")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Build & Run")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Default Build Properties")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Default build directory")," to:",(0,l.kt)("br",null),"\n",(0,l.kt)("inlineCode",{parentName:"p"},'../%{Project:Name}-builds-%{BuildSystem:Name}/%{JS: Util.asciify("build-%{Project:Name}-%{Kit:FileSystemName}-%{BuildConfig:Name}")}'))),(0,l.kt)("h2",{id:"getting-started"},"Getting started"),(0,l.kt)("p",null,"Prepare compilation environment, we need to put the Qt Framework and Visual Studio MSVC compiler on the path on Windows. The compiler is already on the path on Linux and you can export ",(0,l.kt)("inlineCode",{parentName:"p"},"PATH")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," for Qt Framework, or use our ",(0,l.kt)("inlineCode",{parentName:"p"},"qtenvX")," scripts described above."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`mkdir ${(0,k.EA)(y.Fo)}\ncd ${(0,k.EA)(y.Fo)}\n$env:Path = 'C:\\Qt\\6.7.0\\msvc2019_64\\bin;' + $env:Path\nvcvars64.ps1`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`mkdir -p ${(0,k.EA)(y.q5)}\ncd ${(0,k.EA)(y.q5)}\nexport PATH=/opt/Qt/6.7.0/gcc_64/bin\${PATH:+:}$PATH\nexport LD_LIBRARY_PATH=/opt/Qt/6.7.0/gcc_64/lib\${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH`))),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can also use the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/tools/Add-FolderOnPath.ps1"},(0,l.kt)("inlineCode",{parentName:"a"},"tools/Add-FolderOnPath.ps1"))," pwsh script to fastly prepend a path or ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd")," on the system ",(0,l.kt)("inlineCode",{parentName:"p"},"PATH"),".")),(0,l.kt)("h2",{id:"vcpkg"},"vcpkg"),(0,l.kt)("p",null,"Installing the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," is highly recommended, it simplifies installation of the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," dependencies."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},"git clone git@github.com:microsoft/vcpkg.git\ncd vcpkg\n.\\bootstrap-vcpkg.bat\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"git clone git@github.com:microsoft/vcpkg.git\ncd vcpkg\n./bootstrap-vcpkg.sh\n")))),(0,l.kt)("p",null,"Add ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," on the system path, add the following to the ",(0,l.kt)("inlineCode",{parentName:"p"},".bashrc")," or ",(0,l.kt)("inlineCode",{parentName:"p"},".zshrc")," on Linux."),(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export PATH=${(0,k.EA)(y.q5)}/vcpkg\${PATH:+:}$PATH`),(0,l.kt)("p",null,"On Windows, open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Environment variables")," dialog and add ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," on the user ",(0,l.kt)("inlineCode",{parentName:"p"},"PATH"),"."),(0,l.kt)("p",null,"Or you can export it for the current session only."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,k.EA)(y.Fo,!1)}\\vcpkg;" + $env:Path`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export PATH=${(0,k.EA)(y.q5)}/vcpkg\${PATH:+:}$PATH`))),(0,l.kt)("h4",{id:"set-up-vcpkg-environment"},"Set up ",(0,l.kt)("inlineCode",{parentName:"h4"},"vcpkg")," environment"),(0,l.kt)("p",null,"To export ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," environment variables globally, add it to the ",(0,l.kt)("inlineCode",{parentName:"p"},".bashrc")," or ",(0,l.kt)("inlineCode",{parentName:"p"},".zshrc")," on Linux, and you can use the ",(0,l.kt)("inlineCode",{parentName:"p"},"Environment variables")," dialog on Windows."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash",metastring:"title='Linux'",title:"'Linux'"},'export VCPKG_DEFAULT_TRIPLET=x64-linux\n#export VCPKG_DEFAULT_HOST_TRIPLET=x64-linux\nexport VCPKG_MAX_CONCURRENCY=11\nexport VCPKG_OVERLAY_PORTS="$HOME/.local/share/vcpkg/ports"\nexport VCPKG_OVERLAY_TRIPLETS="$HOME/.local/share/vcpkg/triplets"\nexport VCPKG_ROOT="$HOME/Code/c/vcpkg"\n')),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"It is recommended to define these variables globally because the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system are able to detect the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," installation from them so you don't have to configure them manually to detect the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," installation.")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"On Windows, it's always better to create these types of variables as user variables instead of system variables in the ",(0,l.kt)("inlineCode",{parentName:"p"},"Environment variables")," dialog.")),(0,l.kt)("h2",{id:"c-preprocessor-macros"},"C preprocessor macros"),(0,l.kt)("p",null,"The following table summarizes all the C preprocessor macros defined in the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. These C macros are configured by ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build systems. They are not sorted alphabetically, but they are sorted by how significant they are."),(0,l.kt)("p",null,"In the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," build system, all the C macros are auto-detected / auto-configured or controlled by ",(0,l.kt)("a",{parentName:"p",href:"#cmake-build-options"},(0,l.kt)("inlineCode",{parentName:"a"},"CMake build options")),", so you don't have to care too much about them."),(0,l.kt)("p",null,"In the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build is important whether you are building ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library or you are building your application and linking against ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. When you are building the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library, all the C macros are auto-detected / auto-configured or controlled by ",(0,l.kt)("a",{parentName:"p",href:"#qmake-build-options"},(0,l.kt)("inlineCode",{parentName:"a"},"qmake build options")),", so you don't have to care too much about them."),(0,l.kt)("p",null,"But a special situation is when you are building your application / library and you are linking against ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. In this particular case, you must configure all these C macros manually! For this reason, the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/qmake/TinyOrm.pri"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyOrm.pri"))," has been created, so that's not a big deal either. Little more info ",(0,l.kt)("a",{parentName:"p",href:"#consume-tinyorm-library-qmake"},"here"),"."),(0,l.kt)("div",{id:"apitable-c-macros"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"C Macro Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_LINKING_SHARED")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("u",null,(0,l.kt)("strong",{parentName:"td"},"Must"))," be defined when you are linking against ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," shared build (",(0,l.kt)("inlineCode",{parentName:"td"},"dll")," library), exported classes and functions will be tagged with ",(0,l.kt)("inlineCode",{parentName:"td"},"__declspec(dllimport)")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc")," and ",(0,l.kt)("inlineCode",{parentName:"td"},'visibility("default")')," on ",(0,l.kt)("inlineCode",{parentName:"td"},"GCC >= 4"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_BUILDING_SHARED")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined when ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," is built as a ",(0,l.kt)("inlineCode",{parentName:"td"},"dll")," library (shared build).")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DEBUG")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the debug build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_NO_DEBUG")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the release build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DEBUG_SQL")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the debug build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_NO_DEBUG_SQL")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined in the release build.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_MYSQL_PING")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::MySqlConnection::pingDatabase()")," method.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#mysql_ping"},(0,l.kt)("inlineCode",{parentName:"a"},"mysql_ping"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#MYSQL_PING"},(0,l.kt)("inlineCode",{parentName:"a"},"MYSQL_PING"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DISABLE_ORM")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," source code, when this macro is ",(0,l.kt)("inlineCode",{parentName:"td"},"defined"),", then only the ",(0,l.kt)("inlineCode",{parentName:"td"},"query builder")," without ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM")," is compiled. Also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," unit tests.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#disable_orm"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_orm"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#ORM"},(0,l.kt)("inlineCode",{parentName:"a"},"ORM"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled ",(0,l.kt)("small",null,"(qmake)")," / disabled ",(0,l.kt)("small",null,"(cmake)"),"."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_EXTERN_CONSTANTS")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined when extern constants are used. Extern constants are enabled by default for shared builds and disabled for static builds.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Described at ",(0,l.kt)("a",{parentName:"td",href:"#extern_constants"},(0,l.kt)("inlineCode",{parentName:"a"},"qmake"))," / ",(0,l.kt)("a",{parentName:"td",href:"#INLINE_CONSTANTS"},(0,l.kt)("inlineCode",{parentName:"a"},"CMake"))," how it works."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_INLINE_CONSTANTS")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined when global inline constants are used.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#inline_constants"},(0,l.kt)("inlineCode",{parentName:"a"},"inline_constants"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#INLINE_CONSTANTS"},(0,l.kt)("inlineCode",{parentName:"a"},"INLINE_CONSTANTS"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_TESTS_CODE")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable code needed by unit tests, eg. connection overriding in the ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::Tiny::Model"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#build_tests"},(0,l.kt)("inlineCode",{parentName:"a"},"build_tests"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#BUILD_TESTS"},(0,l.kt)("inlineCode",{parentName:"a"},"BUILD_TESTS"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_DISABLE_THREAD_LOCAL")),(0,l.kt)("td",{parentName:"tr",align:null},"Remove all ",(0,l.kt)("a",{parentName:"td",href:"https://en.cppreference.com/w/c/language/storage_duration"},(0,l.kt)("inlineCode",{parentName:"a"},"thread_local"))," storage duration specifiers, it disables multi-threading support.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined when ",(0,l.kt)("a",{parentName:"td",href:"#disable_thread_local"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_thread_local"))," ",(0,l.kt)("small",null,"(qmake)")," / ",(0,l.kt)("a",{parentName:"td",href:"#DISABLE_THREAD_LOCAL"},(0,l.kt)("inlineCode",{parentName:"a"},"DISABLE_THREAD_LOCAL"))," ",(0,l.kt)("small",null,"(cmake)")," configuration ",(0,l.kt)("inlineCode",{parentName:"td"},"build option")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYTOM_MIGRATIONS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Default migrations path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:migration")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/migrations")," ",(0,l.kt)("small",null,"(relative to the pwd)")),(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined by ",(0,l.kt)("a",{parentName:"td",href:"#TOM_MIGRATIONS_DIR"},(0,l.kt)("inlineCode",{parentName:"a"},"TOM_MIGRATIONS_DIR"))," ",(0,l.kt)("small",null,"(cmake)")," configuration build option.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(qmake note) You can use ",(0,l.kt)("inlineCode",{parentName:"td"},'DEFINES += TINYTOM_MIGRATIONS_DIR="\\"database/migrations\\""')," on the command-line or set it in the ",(0,l.kt)("strong",{parentName:"td"},"main")," ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L65-L70"},(0,l.kt)("inlineCode",{parentName:"a"},"conf.pri"))," file.")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYTOM_MODELS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Default models path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:model")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/models")," ",(0,l.kt)("small",null,"(relative to the pwd)")),(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined by ",(0,l.kt)("a",{parentName:"td",href:"#TOM_MODELS_DIR"},(0,l.kt)("inlineCode",{parentName:"a"},"TOM_MODELS_DIR"))," ",(0,l.kt)("small",null,"(cmake)")," configuration build option.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(qmake note) You can use ",(0,l.kt)("inlineCode",{parentName:"td"},'DEFINES += TINYTOM_MODELS_DIR="\\"database/models\\""')," on the command-line or set it in the ",(0,l.kt)("strong",{parentName:"td"},"main")," ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L72-L73"},(0,l.kt)("inlineCode",{parentName:"a"},"conf.pri"))," file.")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYTOM_SEEDERS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Default seeders path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:seeder")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/seeders")," ",(0,l.kt)("small",null,"(relative to the pwd)")),(0,l.kt)("br",null),(0,l.kt)("small",null,"Defined by ",(0,l.kt)("a",{parentName:"td",href:"#TOM_SEEDERS_DIR"},(0,l.kt)("inlineCode",{parentName:"a"},"TOM_SEEDERS_DIR"))," ",(0,l.kt)("small",null,"(cmake)")," configuration build option.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(qmake note) You can use ",(0,l.kt)("inlineCode",{parentName:"td"},'DEFINES += TINYTOM_SEEDERS_DIR="\\"database/seeders\\""')," on the command-line or set it in the ",(0,l.kt)("strong",{parentName:"td"},"main")," ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L75-L76"},(0,l.kt)("inlineCode",{parentName:"a"},"conf.pri"))," file.")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_USING_PCH")),(0,l.kt)("td",{parentName:"tr",align:null},"Defined if building with precompiled headers.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Controlled by ",(0,l.kt)("a",{parentName:"td",href:"#precompile_header"},(0,l.kt)("inlineCode",{parentName:"a"},"qmake"))," / ",(0,l.kt)("a",{parentName:"td",href:"#CMAKE_DISABLE_PRECOMPILE_HEADERS"},(0,l.kt)("inlineCode",{parentName:"a"},"CMake")),"."))))))),(0,l.kt)("h2",{id:"building-with-cmake"},"Building with CMake"),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"If something is not clear, you can still look at GitHub Action ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/.github/workflows"},(0,l.kt)("inlineCode",{parentName:"a"},"workflows"))," how a building is done.")),(0,l.kt)("p",null,"First, create a basic folder structure and then clone the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.Fo)}\nmkdir ${(0,k.AE)()}/TinyORM/TinyORM-builds-cmake/build-debug\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.q5)}\nmkdir -p ${(0,k.AE)()}/TinyORM/TinyORM-builds-cmake/build-debug\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`))),(0,l.kt)("h3",{id:"configure-and-build-cmake"},"Configure & Build ",(0,l.kt)("small",null,"(cmake)")),(0,l.kt)("p",null,"Now you are ready to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd TinyORM-builds-cmake/build-debug\n")),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cmake.exe \`\n-S "${(0,k.go)(y.Fo)}/TinyORM/TinyORM" \`\n-B "${(0,k.go)(y.Fo)}/TinyORM/TinyORM-builds-cmake/build-debug" \`\n-G 'Ninja' \`\n-D CMAKE_BUILD_TYPE:STRING='Debug' \`\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,k.EA)(y.Fo)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \`\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,k.EA)(y.Fo)}/tmp/TinyORM" \`\n-D BUILD_TESTS:BOOL=OFF \`\n-D MATCH_EQUAL_EXPORTED_BUILDTREE:BOOL=ON \`\n-D MYSQL_PING:BOOL=OFF \`\n-D TOM:BOOL=ON \`\n-D TOM_EXAMPLE:BOOL=OFF \`\n-D VERBOSE_CONFIGURE:BOOL=ON`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cmake \\\n-S "${(0,k.go)(y.q5)}/TinyORM/TinyORM" \\\n-B "${(0,k.go)(y.q5)}/TinyORM/TinyORM-builds-cmake/build-debug" \\\n-G 'Ninja' \\\n-D CMAKE_BUILD_TYPE:STRING='Debug' \\\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,k.EA)(y.q5)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \\\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,k.EA)(y.q5)}/tmp/TinyORM" \\\n-D VERBOSE_CONFIGURE:BOOL=ON \\\n-D BUILD_TESTS:BOOL=OFF \\\n-D MYSQL_PING:BOOL=OFF \\\n-D TOM:BOOL=ON \\\n-D TOM_EXAMPLE:BOOL=OFF \\\n-D MATCH_EQUAL_EXPORTED_BUILDTREE:BOOL=ON`))),(0,l.kt)("h5",{id:"cmake-strict_mode-option"},"CMake ",(0,l.kt)("inlineCode",{parentName:"h5"},"STRICT_MODE")," option"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," configuration option was added in ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.37.1"),". This option was added to avoid the propagation of aggressive strict warning compiler/linker options and Qt definitions from the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library to user code through the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/cmake/CommonModules/TinyCommon.cmake"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyOrm::CommonConfig"))," interface library."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," uses the strictest warning level options, virtually anything that can be enabled is enabled to produce a better code. I highly recommend enabling this option to produce better code and to follow good practices. It also helps to follow the ",(0,l.kt)("inlineCode",{parentName:"p"},"ISOCPP")," ",(0,l.kt)("a",{parentName:"p",href:"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines"},"C++ Core Guidelines")," standards."),(0,l.kt)("p",null,"If you want to enable these strict warning options in your code, you can enable the ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," configuration option and they will be propagated to your code. You can also enabled it globally using the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_STRICT_MODE")," environment variable, and the value of this environment variable will be picked up during initial CMake configuration as the default value for the ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," configuration option."),(0,l.kt)("p",null,"You can achieve the same result by manually linking against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm::CommonConfig")," interface library when the ",(0,l.kt)("inlineCode",{parentName:"p"},"STRICT_MODE")," is set to ",(0,l.kt)("inlineCode",{parentName:"p"},"OFF"),"."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-cmake"},"target_link_libraries( PRIVATE TinyOrm::CommonConfig)\n")),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"The recommended way is to set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_STRICT_MODE")," environment variable to ",(0,l.kt)("inlineCode",{parentName:"p"},"1")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"ON"),".")),(0,l.kt)("h4",{id:"build-tinyorm"},"Build TinyORM"),(0,l.kt)("p",null,"And build. You don't have to install it, you can use the build tree directly if you want."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target all\ncmake --install .\n")),(0,l.kt)("p",null,"Or build and install in one step."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target install\n")),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"CMake multi-config generators like ",(0,l.kt)("inlineCode",{parentName:"p"},"Ninja Multi-Config")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"Visual Studio 16 2019")," are also supported.")),(0,l.kt)("h3",{id:"cmake-build-options"},"CMake build options"),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_DRIVERS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyDrivers"))," SQL database drivers (core/common code; replaces QtSql module).")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_MYSQL_DRIVERS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," MySQL database driver.",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_DRIVERS")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_SHARED_LIBS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Build as a shared/static library.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_TESTS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build TinyORM unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_TREE_DEPLOY")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Copy ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyMySql")," libraries to the root of the build tree.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"DRIVERS_TYPE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"Shared")),(0,l.kt)("td",{parentName:"tr",align:null},"How to build and link against ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," SQL database drivers.",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"Static")," value will be select by default when the ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_SHARED_LIBS")," is ",(0,l.kt)("inlineCode",{parentName:"td"},"OFF"),".",(0,l.kt)("br",null),"Supported values: ",(0,l.kt)("inlineCode",{parentName:"td"},"Shared"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"Loadable"),", and ",(0,l.kt)("inlineCode",{parentName:"td"},"Static"),(0,l.kt)("br",null),"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_DRIVERS AND BUILD_SHARED_LIBS")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"INLINE_CONSTANTS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Use inline constants instead of extern constants in the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),".",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"OFF")," is highly recommended for the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),";",(0,l.kt)("br",null),"is always ",(0,l.kt)("inlineCode",{parentName:"td"},"ON")," for the ",(0,l.kt)("inlineCode",{parentName:"td"},"static build"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"BUILD_SHARED_LIBS")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"MSVC_RUNTIME_DYNAMIC")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Use MSVC dynamic runtime library (",(0,l.kt)("inlineCode",{parentName:"td"},"-MD"),") instead of static (",(0,l.kt)("inlineCode",{parentName:"td"},"-MT"),"), also considers a Debug configuration (",(0,l.kt)("inlineCode",{parentName:"td"},"-MTd"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"-MDd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"MSVC AND NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"MYSQL_PING")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::MySqlConnection::pingDatabase()")," method.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ORM")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"disabled"),", then only the ",(0,l.kt)("inlineCode",{parentName:"td"},"query builder")," without ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM")," is compiled. Also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"STRICT_MODE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls propagation of strict compiler/linker options and Qt definitions using the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyOrm::CommonConfig")," interface library to the user code.",(0,l.kt)("br",null),(0,l.kt)("small",null,"(highly recommended; can also be set with the ",(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_STRICT_MODE")," environment variable; described ",(0,l.kt)("a",{parentName:"td",href:"#cmake-strict_mode-option"},"here"),")"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"disabled"),", then it also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_EXAMPLE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build the ",(0,l.kt)("abbr",{title:"TinyORM Migrations"},(0,l.kt)("inlineCode",{parentName:"td"},"tom"))," console application example.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_MIGRATIONS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default migrations path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:migration")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/migrations")," ",(0,l.kt)("small",null,"(relative to the pwd)")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_MODELS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default models path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:model")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/models")," ",(0,l.kt)("small",null,"(relative to the pwd)")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TOM_SEEDERS_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default seeders path for the ",(0,l.kt)("inlineCode",{parentName:"td"},"make:seeder")," command, can be an absolute or relative path (to the ",(0,l.kt)("abbr",{title:"Current working directory"},"pwd"),").",(0,l.kt)("br",null),(0,l.kt)("small",null,"Default value: ",(0,l.kt)("inlineCode",{parentName:"td"},"database/seeders")," ",(0,l.kt)("small",null,"(relative to the pwd)")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"VERBOSE_CONFIGURE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Show information about ",(0,l.kt)("inlineCode",{parentName:"td"},"PACKAGES_FOUND")," / ",(0,l.kt)("inlineCode",{parentName:"td"},"PACKAGES_NOT_FOUND")," in the CMake configure output.")))))),(0,l.kt)("p",null,"Advanced ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"DISABLE_THREAD_LOCAL")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Remove all ",(0,l.kt)("a",{parentName:"td",href:"https://en.cppreference.com/w/c/language/storage_duration"},(0,l.kt)("inlineCode",{parentName:"a"},"thread_local"))," storage duration specifiers, it disables multi-threading support.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("small",null,(0,l.kt)("inlineCode",{parentName:"td"},"MATCH_EQUAL_EXPORTED_BUILDTREE"))),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Exported package configuration from the build tree is considered to match only when ",(0,l.kt)("inlineCode",{parentName:"td"},"the build type")," of application/library that is linking against the TinyORM library ",(0,l.kt)("strong",{parentName:"td"},"is equal"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when:",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_EXPORT_PACKAGE_REGISTRY AND NOT TINY_IS_MULTI_CONFIG")))))))),(0,l.kt)("p",null,"Important ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_DISABLE_PRECOMPILE_HEADERS")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Disable precompiled headers.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_CXX_COMPILER")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"auto")),(0,l.kt)("td",{parentName:"tr",align:null},"The full path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"C++")," compiler.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_CXX_COMPILER_LAUNCHER")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Default compiler launcher to use for the ",(0,l.kt)("inlineCode",{parentName:"td"},"C++")," compiler.",(0,l.kt)("br",null),"Can be used to enable ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache"),", eg. ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache.exe")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"MinGW")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"/usr/bin/ccache")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"Linux"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_EXPORT_PACKAGE_REGISTRY")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable the ",(0,l.kt)("inlineCode",{parentName:"td"},"export(TinyOrm)")," command.",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," sets this variable to ",(0,l.kt)("inlineCode",{parentName:"td"},"ON")," by default.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"CMAKE_VERBOSE_MAKEFILE")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable verbose output from Makefile builds.")))))),(0,l.kt)("h3",{id:"consume-tinyorm-library-cmake"},"Consume TinyOrm library ",(0,l.kt)("small",null,"(cmake)")),(0,l.kt)("p",null,"In your application or library ",(0,l.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file add following ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package()")," call."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-cmake",metastring:"title='CMakeLists.txt'",title:"'CMakeLists.txt'"},"find_package(TinyOrm 0.37.1 CONFIG REQUIRED)\n")),(0,l.kt)("p",null,"If the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build tree is not exported to the CMake's ",(0,l.kt)("a",{parentName:"p",href:"https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#user-package-registry"},(0,l.kt)("inlineCode",{parentName:"a"},"User Package Registry"))," then also add the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build tree or ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_INSTALL_PREFIX")," folder to the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_PREFIX_PATH"),", so CMake can find TinyORM's package configuration file during ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package(TinyOrm)")," call."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:`cmake (${y.Fo})`,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.Fo,(0,k.go)(y.Fo))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\n# installation folder - CMAKE_INSTALL_PREFIX\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.Fo,(0,k.EA)(y.Fo))}/tmp/TinyORM")`)),(0,l.kt)(d.Z,{value:y.q5,label:`cmake (${y.q5})`,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.q5,(0,k.go)(y.q5))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\n# installation folder - CMAKE_INSTALL_PREFIX\nlist(APPEND CMAKE_PREFIX_PATH "${(0,k.we)(y.q5,(0,k.EA)(y.q5))}/tmp/TinyORM")`))),(0,l.kt)("p",null,"Or as an alternative, you can set ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_PREFIX_PATH")," environment variable."),(0,l.kt)("a",{id:"tinyorm-on-path-cmake"}),(0,l.kt)("p",null,"As the last thing, do not forget to add ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm0d.dll")," on the path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so your application can find it during execution."),(0,l.kt)(p.Z,{groupId:y.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,k.go)(y.Fo,!1)}\\TinyORM\\TinyORM-builds-cmake\\build-debug;" + $env:Path`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,k.go)(y.q5)}/TinyORM/TinyORM-builds-cmake/build-debug\${PATH:+:}$PATH`))),(0,l.kt)("p",null,"Now you can try the ",(0,l.kt)("a",{parentName:"p",href:"/building/hello-world#hello-world-with-cmake"},(0,l.kt)("inlineCode",{parentName:"a"},"HelloWorld CMake"))," example."),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"You can also try the ",(0,l.kt)("a",{parentName:"p",href:"/building/hello-world#fetchcontent"},(0,l.kt)("inlineCode",{parentName:"a"},"FetchContent"))," method to fastly link against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library.")),(0,l.kt)("h2",{id:"building-with-qmake"},"Building with qmake"),(0,l.kt)("p",null,"First, create a basic folder structure and then clone the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.Fo)}\nmkdir ${(0,k.AE)()}/TinyORM/TinyORM-builds-qmake\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.EA)(y.q5)}\nmkdir -p ${(0,k.AE)()}/TinyORM/TinyORM-builds-qmake\n\ncd ${(0,k.AE)()}/TinyORM\ngit clone git@github.com:silverqx/TinyORM.git`))),(0,l.kt)("h3",{id:"install-dependencies"},"Install dependencies"),(0,l.kt)("p",null,"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system, you have to install ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," dependencies manually. We will use the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," package manager."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../../vcpkg\n\nvcpkg search range-v3\nvcpkg search tabulate\nvcpkg install range-v3 tabulate\nvcpkg list\n")),(0,l.kt)("p",null,"On ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux"),", you can install the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," library and some other ",(0,l.kt)("a",{parentName:"p",href:"/dependencies#install-dependencies"},"dependencies")," with the package manager."),(0,l.kt)("h3",{id:"configure-and-build-qmake"},"Configure & Build ",(0,l.kt)("small",null,"(qmake)")),(0,l.kt)("h4",{id:"open-qtcreator-ide"},"Open QtCreator IDE"),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"I recommend creating a new ",(0,l.kt)("a",{parentName:"p",href:"https://doc.qt.io/qtcreator/creator-project-managing-sessions.html"},(0,l.kt)("inlineCode",{parentName:"a"},"Session"))," in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator"),", this way you will have all the examples in one place and as a bonus, everything will be in the same place when you close and reopen ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),". You can name it ",(0,l.kt)("inlineCode",{parentName:"p"},"tinyorm.org")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM examples"),", it is up to you.")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"If you are using sessions, you can use a single ",(0,l.kt)("inlineCode",{parentName:"p"},"clangd")," instance for all projects in this session in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),". One significant advantage of this method is that the ",(0,l.kt)("inlineCode",{parentName:"p"},".qtc_clangd/")," folder will not be created in the build folder, but will be stored globally in the Roaming profile. You can enable it in the ",(0,l.kt)("inlineCode",{parentName:"p"},"Settings")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"C++")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Clangd")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Sessions with a single clangd instance"),".")),(0,l.kt)("h4",{id:"configure-tinyorm"},"Configure TinyORM"),(0,l.kt)("p",null,"Now you are ready to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. There are two ways how to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library and it's the new ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configure")," feature added in ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0")," using the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files and the old way using the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files."),(0,l.kt)("h5",{id:"auto-configuration-and-tiny_dotenv"},"Auto-configuration and tiny_dotenv"),(0,l.kt)("p",null,"This is the new recommended method to auto-configure TinyORM's ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system and also the dependencies, it was added in ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0"),". You need to copy the prepared ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw).example")," file to the ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)"),". One ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," example file is prepared for each supported platform."),(0,l.kt)("p",null,"All prepared ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw).example")," files are simple and clear. You can also create a common ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," file that is included before the platform-specific ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)")," files."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.Fo)}/TinyORM/TinyORM\n\ncp .env.win32.example .env.win32`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.q5)}/TinyORM/TinyORM\n\ncp .env.unix.example .env.unix`))),(0,l.kt)("p",null,"And that is all, if you have correctly set all ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variables in this ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)")," file or you have correctly set environment variables, then the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system should be able to ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-detect")," all dependencies . \ud83d\udd25"),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("a",{parentName:"p",href:"#auto-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Auto-configuration"))," and ",(0,l.kt)("a",{parentName:"p",href:"#environment-files"},(0,l.kt)("inlineCode",{parentName:"a"},"Environment files"))," internals are described at the end to make this section more clear.")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_autoconf"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_autoconf"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_autoconf"),").")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_dotenv"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_dotenv"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_dotenv"),").")),(0,l.kt)("h5",{id:"manual-configuration-confpri"},"Manual configuration (conf.pri)"),(0,l.kt)("p",null,"This is the old method used before ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0"),". You need to copy the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri.example")," files to ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," (there are four, one for every project or sub-project) and manually update the ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"LIBS")," to configure TinyORM's ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build dependencies. This way you can override any ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build options or variables."),(0,l.kt)("p",null,"To disable the ",(0,l.kt)("a",{parentName:"p",href:"#auto-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Auto-configuration"))," feature you must define the ",(0,l.kt)("a",{parentName:"p",href:"#disable_autoconf"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_autoconf"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_autoconf"),") because from ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0")," is the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature enabled by default."),(0,l.kt)("p",null,"You can also remove all ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files or turn off the ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature using ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_dotenv"),". You can use them all at once if you want, ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," and also ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files."),(0,l.kt)("p",null,(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are nicely commented on, so you can see what needs to be modified."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.Fo)}/TinyORM/TinyORM\n\ncp conf.pri.example conf.pri\ncp tests/conf.pri.example tests/conf.pri\ncp tests/testdata_tom/conf.pri.example tests/testdata_tom/conf.pri\ncp examples/tom/conf.pri.example examples/tom/conf.pri`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,k.go)(y.q5)}/TinyORM/TinyORM\n\ncp conf.pri.example conf.pri\ncp tests/conf.pri.example tests/conf.pri\ncp tests/testdata_tom/conf.pri.example tests/testdata_tom/conf.pri\ncp examples/tom/conf.pri.example examples/tom/conf.pri`))),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("a",{parentName:"p",href:"#manual-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Manual configuration"))," internals are described at the end to make this section more clear.")),(0,l.kt)("admonition",{type:"note"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Manual configuration")," is still relevant if you have any non-standard installation of the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"MySQL")," and the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature fails.")),(0,l.kt)("h5",{id:"opening-tinyormpro-main-project-file"},"Opening TinyORM.pro (main project file)"),(0,l.kt)("p",null,"Now you can open the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM.pro")," project in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),"."),(0,l.kt)("p",null,"This will open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Configure Project")," tab, select some kit and update build folder paths to meet our ",(0,l.kt)("a",{parentName:"p",href:"#folders-structure"},"folders structure")," or like you want."),(0,l.kt)("img",{src:n(6874).Z,alt:"TinyORM - QtCreator - Configure Project",width:"760"}),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can force the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described ",(0,l.kt)("a",{parentName:"p",href:"#qtcreator-default-build-directory"},"above"),".")),(0,l.kt)("p",null,"You are ready to configure build options, hit ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"5")," to open ",(0,l.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,l.kt)("inlineCode",{parentName:"p"},"Build")," in the left sidebar to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Build Settings"),", it should look similar to the following picture."),(0,l.kt)("p",null,"Disable ",(0,l.kt)("inlineCode",{parentName:"p"},"QML debugging and profiling")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt Quick Compiler"),", they are not used."),(0,l.kt)("img",{src:n(7066).Z,alt:"TinyORM - QtCreator - Build Settings",width:"760"}),(0,l.kt)("p",null,"If you want to change some ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build options, you can pass them to the ",(0,l.kt)("inlineCode",{parentName:"p"},"Build Steps")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake TinyORM.pro")," - ",(0,l.kt)("inlineCode",{parentName:"p"},"Additional arguments")," input field. It can look like this."),(0,l.kt)("img",{src:n(5705).Z,alt:"TinyORM - QtCreator - Build Settings - Additional arguments",width:"660"}),(0,l.kt)("h4",{id:"build-tinyorm-1"},"Build TinyORM"),(0,l.kt)("p",null,"Everything is ready for build, you can press ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"b")," to build the project."),(0,l.kt)("h3",{id:"qmake-build-options"},"qmake build options"),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"th"},"CONFIG")," ",(0,l.kt)("small",null,"Option Name")),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_loadable_drivers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," as a shared library and SQL database drivers (eg. ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyMySql"),") as shared libraries (",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started#the-loadable-sql-drivers-build"},(0,l.kt)("inlineCode",{parentName:"a"},"Loadable"))," modules) that are loaded at runtime using ",(0,l.kt)("inlineCode",{parentName:"td"},"LoadLibrary()")," on Windows or ",(0,l.kt)("inlineCode",{parentName:"td"},"dlopen()")," on Linux.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_mysql_driver")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," MySQL database driver.",(0,l.kt)("br",null),(0,l.kt)("small",null,"It's enabled by default when ",(0,l.kt)("inlineCode",{parentName:"td"},"build_shared_drivers"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"build_loadable_drivers"),", or ",(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")," is enabled.",(0,l.kt)("br",null),"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"build_shared_drivers")," OR ",(0,l.kt)("inlineCode",{parentName:"td"},"build_loadable_drivers")," OR ",(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_shared_drivers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," as a ",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started#the-shared-library-build"},(0,l.kt)("inlineCode",{parentName:"a"},"Shared"))," library.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyDrivers")," as a ",(0,l.kt)("a",{parentName:"td",href:"/tinydrivers/getting-started#the-static-build"},(0,l.kt)("inlineCode",{parentName:"a"},"Static"))," library archive.",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"build_static_drivers")," ",(0,l.kt)("inlineCode",{parentName:"td"},"qmake")," configuration option will be select by default when the ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG*=staticlib")," is enabled."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"build_tests")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build TinyORM unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_autoconf")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Disable the ",(0,l.kt)("a",{parentName:"td",href:"#auto-configuration-internals"},(0,l.kt)("inlineCode",{parentName:"a"},"Auto-configuration"))," feature ",(0,l.kt)("small",null,"(auto-configuration is enabled by default from ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"td"},"v0.34.0"),")"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_dotenv")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Disable the ",(0,l.kt)("a",{parentName:"td",href:"#environment-files"},(0,l.kt)("inlineCode",{parentName:"a"},"tiny_dotenv"))," feature ",(0,l.kt)("small",null,"(environment files are enabled by default from ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"td"},"v0.34.0"),")"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_thread_local")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Remove all ",(0,l.kt)("a",{parentName:"td",href:"https://en.cppreference.com/w/c/language/storage_duration"},(0,l.kt)("inlineCode",{parentName:"a"},"thread_local"))," storage duration specifiers, it disables multi-threading support.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_orm")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"enabled"),", then only the ",(0,l.kt)("inlineCode",{parentName:"td"},"query builder")," without ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM")," is compiled. Also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"ORM-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"disable_tom")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Controls the compilation of all ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," source code, when this option is ",(0,l.kt)("inlineCode",{parentName:"td"},"disabled"),", then it also excludes ",(0,l.kt)("inlineCode",{parentName:"td"},"Tom-related")," unit tests.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"extern_constants")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Use ",(0,l.kt)("inlineCode",{parentName:"td"},"extern")," constants instead of ",(0,l.kt)("inlineCode",{parentName:"td"},"inline")," constants in the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),".",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"ON")," is highly recommended for the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build")," ",(0,l.kt)("small",null,"(by default)"),";",(0,l.kt)("br",null),"is always ",(0,l.kt)("inlineCode",{parentName:"td"},"OFF")," for the ",(0,l.kt)("inlineCode",{parentName:"td"},"static build"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("code",null,"CONFIG(shared","|","dll):!inline_constants")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"inline_constants")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Use ",(0,l.kt)("inlineCode",{parentName:"td"},"inline")," constants instead of ",(0,l.kt)("inlineCode",{parentName:"td"},"extern")," constants in the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),".",(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"OFF")," is highly recommended for the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared build"),";",(0,l.kt)("br",null),"is always ",(0,l.kt)("inlineCode",{parentName:"td"},"ON")," for the ",(0,l.kt)("inlineCode",{parentName:"td"},"static build"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"link_pkgconfig_off")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Link against ",(0,l.kt)("inlineCode",{parentName:"td"},"mysqlclient")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"libmariadb")," with ",(0,l.kt)("inlineCode",{parentName:"td"},"PKGCONFIG"),".",(0,l.kt)("br",null),"Used only in the ",(0,l.kt)("inlineCode",{parentName:"td"},"Unix")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"MinGW")," ",(0,l.kt)("strong",{parentName:"td"},"shared")," build ",(0,l.kt)("small",null,"(exactly ",(0,l.kt)("code",null,"win32-g++","|","win32-clang-g++"),")")," and when ",(0,l.kt)("inlineCode",{parentName:"td"},"mysql_ping")," is also defined to link against ",(0,l.kt)("inlineCode",{parentName:"td"},"mysqlclient")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"libmariadb"),", ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/conf.pri.example#L132"},"source code"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"unix:mysql_ping")," or ",(0,l.kt)("code",null,"(win32-g++","|","win32-clang-g++):mysql_ping:!static:!staticlib")))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"mysql_ping")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable ",(0,l.kt)("inlineCode",{parentName:"td"},"Orm::MySqlConnection::pingDatabase()")," method.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"tiny_ccache_win32")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ON")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable compiler cache. ",(0,l.kt)("a",{parentName:"td",href:"https://ccache.dev/"},"Homepage"),(0,l.kt)("br",null),(0,l.kt)("small",null,"It works only on Windows systems. It works well with the MSYS2 ",(0,l.kt)("inlineCode",{parentName:"td"},"g++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"clang++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc"),", and ",(0,l.kt)("inlineCode",{parentName:"td"},"clang-cl")," with ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc"),". It disables ",(0,l.kt)("inlineCode",{parentName:"td"},"precompile_header")," as they are not supported on Windows and changes the ",(0,l.kt)("inlineCode",{parentName:"td"},"-Zi")," compiler option to the ",(0,l.kt)("inlineCode",{parentName:"td"},"-Z7")," for debug builds as the ",(0,l.kt)("inlineCode",{parentName:"td"},"-Zi")," compiler option is not supported (",(0,l.kt)("a",{parentName:"td",href:"https://github.com/ccache/ccache/issues/1040"},"link")," to the issue)."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"tom_example")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build the ",(0,l.kt)("abbr",{title:"TinyORM Migrations"},(0,l.kt)("inlineCode",{parentName:"td"},"tom"))," console application example.")))))),(0,l.kt)("p",null,"Advanced ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Option Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ubsan")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Allows to enable ",(0,l.kt)("a",{parentName:"td",href:"https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html"},"UBSan")," sanitizer (Clang only).")))))),(0,l.kt)("p",null,"Important ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," options."),(0,l.kt)("div",{className:"apitable-build-options"},(0,l.kt)(r.Z,{mdxType:"APITable"},(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"th"},"CONFIG")," ",(0,l.kt)("small",null,"Option Name")),(0,l.kt)("th",{parentName:"tr",align:null},"Default"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"ccache")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable compiler cache. ",(0,l.kt)("a",{parentName:"td",href:"https://ccache.dev/"},"Homepage"),(0,l.kt)("br",null),(0,l.kt)("small",null,"It works only on the Unix systems. It works well with the ",(0,l.kt)("inlineCode",{parentName:"td"},"g++")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"clang++")," and also supports precompiled headers."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"precompile_header")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"-")),(0,l.kt)("td",{parentName:"tr",align:null},"Enable precompiled headers, you can disable them with:",(0,l.kt)("br",null)," ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG-=precompile_header"),".",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"precompile_header")," is enabled by default on ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"g++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"clang++"),", ",(0,l.kt)("inlineCode",{parentName:"td"},"clang-cl")," on ",(0,l.kt)("inlineCode",{parentName:"td"},"Windows")," and disabled by default on ",(0,l.kt)("inlineCode",{parentName:"td"},"linux"),"."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"static"),(0,l.kt)("br",null),(0,l.kt)("inlineCode",{parentName:"td"},"staticlib")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Build as a ",(0,l.kt)("inlineCode",{parentName:"td"},"static")," library (lib only).",(0,l.kt)("br",null),(0,l.kt)("small",null,"If you want to build all libraries in the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," project as static library archives and link against static libraries use the ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG += static"),". Don't use the ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG += staticlib"),".",(0,l.kt)("br",null),"See ",(0,l.kt)("a",{parentName:"td",href:"https://github.com/silverqx/TinyORM/blob/main/NOTES.txt"},"NOTES.txt")," for more information (search ",(0,l.kt)("inlineCode",{parentName:"td"},"static vs staticlib"),")."))),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"static_runtime")),(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"OFF")),(0,l.kt)("td",{parentName:"tr",align:null},"Link against the ",(0,l.kt)("inlineCode",{parentName:"td"},"shared")," (dynamic) or ",(0,l.kt)("inlineCode",{parentName:"td"},"static")," run-time library.",(0,l.kt)("br",null),(0,l.kt)("small",null,"The ",(0,l.kt)("inlineCode",{parentName:"td"},"-MD")," becomes ",(0,l.kt)("inlineCode",{parentName:"td"},"-MT")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"-MDd")," becomes ",(0,l.kt)("inlineCode",{parentName:"td"},"-MTd"),". It works only on ",(0,l.kt)("inlineCode",{parentName:"td"},"MSVC")," and ",(0,l.kt)("inlineCode",{parentName:"td"},"MinGW")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"MSYS2"),".",(0,l.kt)("br",null),"Please ",(0,l.kt)("u",null,"don't use")," this option.",(0,l.kt)("br",null),"Available when: ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc")," or ",(0,l.kt)("inlineCode",{parentName:"td"},"mingw")))))))),(0,l.kt)("h3",{id:"consume-tinyorm-library-qmake"},"Consume TinyOrm library ",(0,l.kt)("small",null,"(qmake)")),(0,l.kt)("p",null,"The ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/qmake/TinyOrm.pri"},(0,l.kt)("inlineCode",{parentName:"a"},"TinyOrm.pri"))," file is available to simplify the integration of the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library into your application. It sets up and configures the ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"DEFINES")," qmake variables, adds the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM"),", ",(0,l.kt)("abbr",{title:"TinyORM Migrations"},(0,l.kt)("inlineCode",{parentName:"p"},"tom")),", and ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," header files on the system ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," (cross-platform using the ",(0,l.kt)("inlineCode",{parentName:"p"},"-isystem")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"-imsvc"),"), links against the TinyORM ",(0,l.kt)("inlineCode",{parentName:"p"},"shared")," or ",(0,l.kt)("inlineCode",{parentName:"p"},"static")," library using the ",(0,l.kt)("inlineCode",{parentName:"p"},"LIBS"),"."),(0,l.kt)("p",null,"You can use it to configure the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library when you are linking against it. It does a very similar thing like the CMake's ",(0,l.kt)("inlineCode",{parentName:"p"},"Find Modules")," feature."),(0,l.kt)("h4",{id:"requirements"},"Requirements"),(0,l.kt)("p",null,"It has a few requirements, you need to:"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},"specify path to the ",(0,l.kt)("inlineCode",{parentName:"li"},"TinyORM")," qmake features (",(0,l.kt)("inlineCode",{parentName:"li"},".prf")," files) using the ",(0,l.kt)("inlineCode",{parentName:"li"},"QMAKEFEATURES")," variable that can only be set in the ",(0,l.kt)("inlineCode",{parentName:"li"},".qmake.conf")," file"),(0,l.kt)("li",{parentName:"ul"},"specify ",(0,l.kt)("inlineCode",{parentName:"li"},"qmake")," or ",(0,l.kt)("inlineCode",{parentName:"li"},"environment")," variables to find the ",(0,l.kt)("inlineCode",{parentName:"li"},"vcpkg")," installation ",(0,l.kt)("small",null,"(",(0,l.kt)("inlineCode",{parentName:"li"},"TINY_VCPKG_ROOT")," and ",(0,l.kt)("inlineCode",{parentName:"li"},"TINY_VCPKG_TRIPLET"),")")),(0,l.kt)("li",{parentName:"ul"},"specify path to the ",(0,l.kt)("inlineCode",{parentName:"li"},"TinyORM")," build folder ",(0,l.kt)("small",null,"(",(0,l.kt)("inlineCode",{parentName:"li"},"TINYORM_BUILD_TREE"),")"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},"you can specify it ",(0,l.kt)("strong",{parentName:"li"},"manually")),(0,l.kt)("li",{parentName:"ul"},"or you can use ",(0,l.kt)("a",{parentName:"li",href:"#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))))),(0,l.kt)("li",{parentName:"ul"},"build your application with the same ",(0,l.kt)("inlineCode",{parentName:"li"},"CONFIG")," ",(0,l.kt)("inlineCode",{parentName:"li"},"qmake")," variables that were used when building the ",(0,l.kt)("inlineCode",{parentName:"li"},"TinyORM")," library")),(0,l.kt)("p",null,"Let's explain one by one."),(0,l.kt)("h5",{id:"qmakefeatures"},(0,l.kt)("inlineCode",{parentName:"h5"},"QMAKEFEATURES")),(0,l.kt)("p",null,"Create the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file in your application root folder with the following content."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the PARENT folder of the TinyORM source folder\nTINY_MAIN_DIR = $$clean_path()\n# To find .env and .env.$$QMAKE_PLATFORM files in YOUR project\nTINY_DOTENV_ROOT = $$PWD\n\n# Path to the TinyORM build folder (specified manually)\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/)\n# vcpkg - range-v3 and tabulate\nTINY_VCPKG_ROOT = $$quote(/vcpkg/)\n#TINY_VCPKG_TRIPLET = x64-windows\n\n# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants\nQMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)\n")),(0,l.kt)("p",null,"You can move all ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variables that are part of the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration process to the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," file if you want (recommended), this is possible because the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," enables the ",(0,l.kt)("a",{parentName:"p",href:"#environment-files"},(0,l.kt)("inlineCode",{parentName:"a"},"Environment files"))," feature by default."),(0,l.kt)("p",null,"You can look at the ",(0,l.kt)("a",{parentName:"p",href:"/building/hello-world#auto-configure-using-qmake_conf-and-env"},"Auto-configure using .qmake.conf and .env")," example for ",(0,l.kt)("inlineCode",{parentName:"p"},"Hello world")," project of what must stay in the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake.conf")," file and what can be moved to the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can use the ",(0,l.kt)("a",{parentName:"p",href:"#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," if you don't like to specify it manually.")),(0,l.kt)("h5",{id:"variables-affecting-tinyormpri"},"Variables affecting ",(0,l.kt)("inlineCode",{parentName:"h5"},"TinyOrm.pri")),(0,l.kt)("p",null,"You must define the following variables before the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," is included:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINYORM_BUILD_TREE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," build folder.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_ROOT")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," installation folder.",(0,l.kt)("br",null),"If not defined, then it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_ROOT")," environment variable.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_TRIPLET")),(0,l.kt)("td",{parentName:"tr",align:null},"The ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," to use ",(0,l.kt)("small",null,"(vcpkg/installed/$$TINY_VCPKG_TRIPLET/)"),".",(0,l.kt)("br",null),"If not defined, then it tries to guess the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," based on the current compiler and OS (based on the ",(0,l.kt)("inlineCode",{parentName:"td"},"QMAKESPEC"),"), and as the last thing, it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_DEFAULT_TRIPLET")," environment variable.")))),(0,l.kt)("p",null,"These variables will be set after the configuration is done:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_BUILD_SUBFOLDER")),(0,l.kt)("td",{parentName:"tr",align:null},"Folder by release type if ",(0,l.kt)("inlineCode",{parentName:"td"},"CONFIG+=debug_and_release")," is defined ",(0,l.kt)("small",null,"(/debug, /release, or an empty string)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_CCACHE_BUILD")),(0,l.kt)("td",{parentName:"tr",align:null},"To correctly link ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache")," build against a ",(0,l.kt)("inlineCode",{parentName:"td"},"ccache")," build ",(0,l.kt)("small",null,"(_ccache or an empty string)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MSVC_VERSION")),(0,l.kt)("td",{parentName:"tr",align:null},"The ",(0,l.kt)("inlineCode",{parentName:"td"},"msvc")," compiler string ",(0,l.kt)("small",null,"(MSVC2022 or MSVC2019)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_QT_VERSION_UNDERSCORED")),(0,l.kt)("td",{parentName:"tr",align:null},"Underscored ",(0,l.kt)("inlineCode",{parentName:"td"},"Qt")," version ",(0,l.kt)("small",null,"(eg. 6_7_0)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_RELEASE_TYPE_CAMEL")),(0,l.kt)("td",{parentName:"tr",align:null},"Build type string ",(0,l.kt)("small",null,"(Debug, Profile, or Release)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_INCLUDE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"include")," folder ",(0,l.kt)("small",null,"(vcpkg/installed/","<","triplet",">","/include/)"),".")))),(0,l.kt)("p",null,"Then you simply include the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," in your project file."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='AnyProject.pro'",title:"'AnyProject.pro'"},"include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n")),(0,l.kt)("p",null,"And that is all, now you should be able to link against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. \ud83d\udc4c"),(0,l.kt)("h5",{id:"manual-configuration-examples"},"Manual configuration examples"),(0,l.kt)("p",null,"Frankly, there is no reason to use the Manual configuration (define the variables described below before the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," inclusion), the only reason to use it is when you want more control over this process or want to define everything yourself. I'll leave this section here to show how things work."),(0,l.kt)("p",null,"You will have to link against the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library manually if you don't set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variable before the inclusion of the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," file. The ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," is auto-detected every time."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"{9}","{9}":!0},"# Link against TinyORM library\n# ---\nTINY_MAIN_DIR = $$clean_path()\n\n# Configure TinyORM library\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n\n# TinyORM library path\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake)\nLIBS += $$quote(-L$$TINYORM_BUILD_TREE/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/src$${TINY_BUILD_SUBFOLDER}/)\nLIBS += -lTinyOrm\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"{9}","{9}":!0},"# Link against TinyORM library\n# ---\nTINY_MAIN_DIR = $$clean_path()\n\n# Configure TinyORM library\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n\n# TinyORM library path\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake)\nLIBS += $$quote(-L$$TINYORM_BUILD_TREE/build-TinyORM-Desktop_Qt_6_7_0_GCC_64bit-Debug/src$${TINY_BUILD_SUBFOLDER}/)\nLIBS += -lTinyOrm\n")))),(0,l.kt)("p",null,"The same is true for the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," include path. If you don't set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_VCPKG_ROOT")," or have not defined the ",(0,l.kt)("inlineCode",{parentName:"p"},"VCPKG_ROOT")," environment variable, then you need to set up the ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," for the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," that provides the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," header files."),(0,l.kt)(p.Z,{groupId:y.IZ,mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# vcpkg - range-v3 and tabulate\n# ---\nINCLUDEPATH += $$quote(/vcpkg/installed/x64-windows/include/)\n"))),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# vcpkg - range-v3 and tabulate\n# ---\nQMAKE_CXXFLAGS += -isystem $$shell_quote(/vcpkg/installed/x64-linux/include/)\n")))),(0,l.kt)("p",null,"You can also use TinyORM's ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," function ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_add_system_includepath()")," which handles ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," in a cross-platform way."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# vcpkg - range-v3 and tabulate\n# ---\nload(tiny_system_includepath)\ntiny_add_system_includepath(/vcpkg/installed/x64-linux/include/)\n")),(0,l.kt)("p",null,"Do not forget to add ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm0.dll")," on the path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so your application can find it during execution."),(0,l.kt)(p.Z,{groupId:y.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,l.kt)(d.Z,{value:y.Fo,label:y.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,k.go)(y.Fo,!1)}\\TinyORM\\TinyORM-builds-qmake\\build-debug;" + $env:Path`)),(0,l.kt)(d.Z,{value:y.q5,label:y.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,k.go)(y.q5)}/TinyORM/TinyORM-builds-qmake/build-debug\${PATH:+:}$PATH`))),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"On Linux ",(0,l.kt)("inlineCode",{parentName:"p"},"-isystem")," marks the directory as a system directory, it prevents warnings."),(0,l.kt)("p",{parentName:"admonition"},"On Windows you can use ",(0,l.kt)("inlineCode",{parentName:"p"},"QMAKE_CXXFLAGS_WARN_ON = -external:anglebrackets -external:W0"),", it applies a warning level 0 to the angel bracket includes; ",(0,l.kt)("inlineCode",{parentName:"p"},"#include "),"."),(0,l.kt)("p",{parentName:"admonition"},"With the ",(0,l.kt)("inlineCode",{parentName:"p"},"clang-cl")," with ",(0,l.kt)("inlineCode",{parentName:"p"},"MSVC")," you can use ",(0,l.kt)("inlineCode",{parentName:"p"},"-imsvc"),".")),(0,l.kt)("h3",{id:"auto-configuration-internals"},"Auto-configuration internals"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build system does not support ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-configuration")," of dependencies out of the box but ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," from ",(0,l.kt)("inlineCode",{parentName:"p"},"v0.34.0")," added its own ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature along with the ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," qmake feature. These new features allow us to ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-configure")," ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project, and with their help, the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files can be ",(0,l.kt)("u",null,"skipped entirely"),"."),(0,l.kt)("p",null,"While it adds additional complexity to the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration process, the benefits are significant."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature is designed to find the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"MySQL")," installations, and ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," to include the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," and ",(0,l.kt)("inlineCode",{parentName:"p"},".env.(win32|unix|mingw)")," files in the project's root folder. These new features can be configured using ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"environment")," variables, and they also contain some guessing logic if these variables are not defined."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_autoconf"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_autoconf"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_autoconf"),")."),(0,l.kt)("p",null,"These are ",(0,l.kt)("u",null,(0,l.kt)("inlineCode",{parentName:"p"},"qmake"))," and ",(0,l.kt)("u",null,(0,l.kt)("inlineCode",{parentName:"p"},"environment"))," variables that affect the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_ROOT")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," installation folder.",(0,l.kt)("br",null),"If not defined, then it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_ROOT")," environment variable.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_TRIPLET")),(0,l.kt)("td",{parentName:"tr",align:null},"The ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," to use ",(0,l.kt)("small",null,"(vcpkg/installed/$$TINY_VCPKG_TRIPLET/)"),".",(0,l.kt)("br",null),"If not defined, then it tries to guess the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"triplet")," based on the current compiler and OS (based on the ",(0,l.kt)("inlineCode",{parentName:"td"},"QMAKESPEC"),"), and as the last thing, it tries to use the ",(0,l.kt)("inlineCode",{parentName:"td"},"VCPKG_DEFAULT_TRIPLET")," environment variable.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MYSQL_ROOT")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," installation folder.",(0,l.kt)("br",null),"If not defined, then it tries to guess the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," installation folder (",(0,l.kt)("inlineCode",{parentName:"td"},"win32")," only): ",(0,l.kt)("code",null,"$$(ProgramFiles)/MySQL/MySQL Server (8.3","|","8.2","|","8.1","|","8.0","|","5.7)/"))))),(0,l.kt)("p",null,"You can set these variables in the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," (recommended) or ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files, in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file (or wherever you want), or as environment variables."),(0,l.kt)("p",null,"These variables will be set after ",(0,l.kt)("inlineCode",{parentName:"p"},"auto-configuration")," is done:"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_VCPKG_INCLUDE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"vcpkg")," ",(0,l.kt)("inlineCode",{parentName:"td"},"include")," folder ",(0,l.kt)("small",null,"(vcpkg/installed/","<","triplet",">","/include/)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MYSQL_INCLUDE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," ",(0,l.kt)("inlineCode",{parentName:"td"},"include")," folder ",(0,l.kt)("small",null,"(MySQL Server 8.3/include/)"),".")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MYSQL_LIB")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("inlineCode",{parentName:"td"},"MySQL")," ",(0,l.kt)("inlineCode",{parentName:"td"},"lib")," folder ",(0,l.kt)("small",null,"(MySQL Server 8.3/lib/)"),".")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_MYSQL_INCLUDE")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_MYSQL_LIB")," are only set on ",(0,l.kt)("inlineCode",{parentName:"p"},"win32")," platform except ",(0,l.kt)("inlineCode",{parentName:"p"},"mingw"),"."),(0,l.kt)("h4",{id:"environment-files"},"Environment files"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature allows us to define the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," and ",(0,l.kt)("inlineCode",{parentName:"p"},".env.$$TINY_DOTENV_PLATFORM")," files in the project's root folder. These files are loaded as early as possible so you can affect the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration process. On the other hand, the ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are loaded as late as possible, and they can be used to override the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," file is included ",(0,l.kt)("u",null,"first")," and is included on all platforms."),(0,l.kt)("p",null,"There is only one requirement for this feature to work correctly, and that is to set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_DOTENV_ROOT")," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," variable to the project's root folder. This variable is ",(0,l.kt)("strong",{parentName:"p"},"already")," set in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file for the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project."),(0,l.kt)("p",null,"Then the following names are taken into account: .env, .env.win32, .env.unix, .env.mingw"),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# To find .env and .env.$$QMAKE_PLATFORM files\nTINY_DOTENV_ROOT = $$PWD\n")),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"tiny_dotenv")," feature can be turned off using the ",(0,l.kt)("a",{parentName:"p",href:"#disable_dotenv"},(0,l.kt)("inlineCode",{parentName:"a"},"disable_dotenv"))," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration option (eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG*=disable_dotenv"),")."),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},(0,l.kt)("inlineCode",{parentName:"p"},"Environment files")," don't work in the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," builds.")),(0,l.kt)("h4",{id:"partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"h4"},"TINYORM_BUILD_TREE")),(0,l.kt)("p",null,"You don't have to manually define the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," in ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," or ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," files. The ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," absolute path can be put together for you (this is happening inside the ",(0,l.kt)("inlineCode",{parentName:"p"},"variables.pri")," file) and ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build folder name can be guessed for you too."),(0,l.kt)("p",null,"You must define the following variables before the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm.pri")," will be included to make this real (set them in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf"),"):"),(0,l.kt)("table",null,(0,l.kt)("thead",{parentName:"table"},(0,l.kt)("tr",{parentName:"thead"},(0,l.kt)("th",{parentName:"tr",align:null},"Variable Name"),(0,l.kt)("th",{parentName:"tr",align:null},"Description"))),(0,l.kt)("tbody",{parentName:"table"},(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_MAIN_DIR")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("strong",{parentName:"td"},"PARENT")," folder of the ",(0,l.kt)("inlineCode",{parentName:"td"},"TinyORM")," source folder.")),(0,l.kt)("tr",{parentName:"tbody"},(0,l.kt)("td",{parentName:"tr",align:null},(0,l.kt)("inlineCode",{parentName:"td"},"TINY_BUILD_TREE")),(0,l.kt)("td",{parentName:"tr",align:null},"Path to the ",(0,l.kt)("strong",{parentName:"td"},"current")," build tree - ",(0,l.kt)("inlineCode",{parentName:"td"},"TINY_BUILD_TREE = $$shadowed($$PWD)"),".")))),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_MAIN_DIR")," is required for another features anyway (so it should already be set) and all that's left is to set the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_BUILD_TREE"),"."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the current build tree (used to guess the TinyORM build tree)\nTINY_BUILD_TREE = $$shadowed($$PWD)\n")),(0,l.kt)("p",null,"If you will follow this pattern or logic then you can switch ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator Kits")," and the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," will be ",(0,l.kt)("strong",{parentName:"p"},"auto-generated")," correctly and will always point to the correct ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build tree."),(0,l.kt)("p",null,"It works this way, all is happening inside the ",(0,l.kt)("inlineCode",{parentName:"p"},"variables.pri"),", it takes a build folder name for the ",(0,l.kt)("strong",{parentName:"p"},"current")," project eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"build-HelloWorld-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug"),", replaces the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," with the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," and as we already know the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," build folder location we can simply concatenate these paths like ",(0,l.kt)("inlineCode",{parentName:"p"},"$$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug"),"."),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"This will only work if you follow the recommended ",(0,l.kt)("a",{parentName:"p",href:"#folders-structure"},(0,l.kt)("inlineCode",{parentName:"a"},"Folders structure")),".")),(0,l.kt)("h3",{id:"manual-configuration-internals"},"Manual configuration internals"),(0,l.kt)("p",null,"There is not much to say about the ",(0,l.kt)("inlineCode",{parentName:"p"},"Manual configuration")," feature. It uses ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files (there are four, one for every project or sub-project), and every project has prepared its own ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri.example")," file for faster initial configuration."),(0,l.kt)("p",null,"These ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri.example")," files are nicely commented on, so you can see what needs to be modified. The ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are loaded as late as possible, and they can be used to override the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration."),(0,l.kt)("p",null,"If the ",(0,l.kt)("inlineCode",{parentName:"p"},"Auto-configuration")," feature is disabled and there are no ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files, then the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," configuration or build will fail at 100%."),(0,l.kt)("p",null,"These ",(0,l.kt)("inlineCode",{parentName:"p"},"conf.pri")," files are intended for configuring qmake's ",(0,l.kt)("inlineCode",{parentName:"p"},"INCLUDEPATH")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"LIBS"),", ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG")," or eg. ",(0,l.kt)("inlineCode",{parentName:"p"},"QMAKE_LFLAGS"),", or any other ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," options or variables."),(0,l.kt)("h2",{id:"ccache-support"},"Ccache support"),(0,l.kt)("p",null,"The TinyORM supports the ",(0,l.kt)("a",{parentName:"p",href:"https://ccache.dev/"},(0,l.kt)("inlineCode",{parentName:"a"},"ccache"))," out of the box for all ",(0,l.kt)("a",{parentName:"p",href:"/supported-compilers"},"supported compilers"),". For qmake you can enable it using the ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG+=ccache")," on Linux or ",(0,l.kt)("inlineCode",{parentName:"p"},"CONFIG+=tiny_ccache_win32")," on Windows. For CMake you can set the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_CXX_COMPILER_LAUNCHER=ccache"),"."),(0,l.kt)("p",null,"On ",(0,l.kt)("inlineCode",{parentName:"p"},"Linux")," it's clear, the ccache is fully supported and works also with the ",(0,l.kt)("inlineCode",{parentName:"p"},"precompiled headers"),". But was necessary to add some workarounds to the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake"),"/",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," build systems to make out of the box support on ",(0,l.kt)("inlineCode",{parentName:"p"},"Windows"),". When you enable the ",(0,l.kt)("inlineCode",{parentName:"p"},"ccache")," on ",(0,l.kt)("inlineCode",{parentName:"p"},"Windows")," then the build system disables ",(0,l.kt)("inlineCode",{parentName:"p"},"precompiled headers")," and replaces the ",(0,l.kt)("inlineCode",{parentName:"p"},"-Zi")," compiler option with the ",(0,l.kt)("inlineCode",{parentName:"p"},"-Z7")," (link to the ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/ccache/ccache/issues/1040"},"issue"),")."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can install the ccache using the ",(0,l.kt)("inlineCode",{parentName:"p"},"scoop install ccache")," command on Windows.")))}R.isMDXComponent=!0},5705:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-additional_arguments-14d3b6b82ad6d28db5b999a462500a6a.png"},7066:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-build_settings-7caa6d7c86232484b82acb24b5a3a6a7.png"},6874:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-configure_project-0b6821ea0523567dab9f21b3215055a3.png"}}]); \ No newline at end of file diff --git a/assets/js/59b1a96c.6afbbfdf.js b/assets/js/59b1a96c.79c5818c.js similarity index 98% rename from assets/js/59b1a96c.6afbbfdf.js rename to assets/js/59b1a96c.79c5818c.js index 84aaf9e88..437fe244b 100644 --- a/assets/js/59b1a96c.6afbbfdf.js +++ b/assets/js/59b1a96c.79c5818c.js @@ -1 +1 @@ -"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[67],{3905:(e,t,a)=>{a.d(t,{Zo:()=>m,kt:()=>y});var r=a(7294);function n(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function i(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,r)}return a}function o(e){for(var t=1;t=0||(n[a]=e[a]);return n}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(n[a]=e[a])}return n}var s=r.createContext({}),p=function(e){var t=r.useContext(s),a=t;return e&&(a="function"==typeof e?e(t):o(o({},t),e)),a},m=function(e){var t=p(e.components);return r.createElement(s.Provider,{value:t},e.children)},u="mdxType",d={inlineCode:"code",wrapper:function(e){var t=e.children;return r.createElement(r.Fragment,{},t)}},c=r.forwardRef((function(e,t){var a=e.components,n=e.mdxType,i=e.originalType,s=e.parentName,m=l(e,["components","mdxType","originalType","parentName"]),u=p(a),c=n,y=u["".concat(s,".").concat(c)]||u[c]||d[c]||i;return a?r.createElement(y,o(o({ref:t},m),{},{components:a})):r.createElement(y,o({ref:t},m))}));function y(e,t){var a=arguments,n=t&&t.mdxType;if("string"==typeof e||n){var i=a.length,o=new Array(i);o[0]=c;var l={};for(var s in t)hasOwnProperty.call(t,s)&&(l[s]=t[s]);l.originalType=e,l[u]="string"==typeof e?e:n,o[1]=l;for(var p=2;p{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));const i={sidebar_position:0,sidebar_label:"\ud83d\udd25 Prologue",slug:"/",hide_table_of_contents:!0,description:"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries. The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests.",keywords:["c++ orm","prologue","tinyorm"]},o="Prologue",l={unversionedId:"README",id:"README",title:"Prologue",description:"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries. The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests.",source:"@site/docs/README.mdx",sourceDirName:".",slug:"/",permalink:"/",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/README.mdx",tags:[],version:"current",sidebarPosition:0,frontMatter:{sidebar_position:0,sidebar_label:"\ud83d\udd25 Prologue",slug:"/",hide_table_of_contents:!0,description:"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries. The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests.",keywords:["c++ orm","prologue","tinyorm"]},sidebar:"tinyormSidebar",next:{title:"\ud83d\udd27 Dependencies",permalink:"/dependencies"}},s={},p=[{value:"Documentation Sitemap",id:"documentation-sitemap",level:5},{value:"Current versions",id:"current-versions",level:5}],m={toc:p},u="wrapper";function d(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("h1",{id:"prologue"},"Prologue"),(0,n.kt)("p",null,"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the ",(0,n.kt)("inlineCode",{parentName:"p"},"QtCore")," and ",(0,n.kt)("inlineCode",{parentName:"p"},"QtSql")," libraries."),(0,n.kt)("p",null,"The code is written in the modern C++20 way and is ",(0,n.kt)("strong",{parentName:"p"},"heavily")," tested with ",(0,n.kt)("strong",{parentName:"p"},"3366")," unit and functional tests. Almost all the query builder methods are unit tested. The TinyORM's query builder code and the code which is responsible for obtaining relationships, is tested by functional tests against all supported databases. The code coverage is good enough to guarantee API and behavior compatibility."),(0,n.kt)("admonition",{type:"tip"},(0,n.kt)("p",{parentName:"admonition"},"For a quick look at what's inside, check out the ",(0,n.kt)("a",{parentName:"p",href:"/features-summary"},"Features Summary"),".")),(0,n.kt)("admonition",{type:"info"},(0,n.kt)("p",{parentName:"admonition"},"If you don't want to use full ",(0,n.kt)("a",{parentName:"p",href:"/tinyorm/getting-started"},(0,n.kt)("inlineCode",{parentName:"a"},"ORM")),", then you can use only the ",(0,n.kt)("a",{parentName:"p",href:"/database/query-builder"},(0,n.kt)("inlineCode",{parentName:"a"},"Query Builder")),", which is outstanding. \ud83d\udd25 This way you can avoid writing raw SQL queries and your code will run on all ",(0,n.kt)("a",{parentName:"p",href:"/database/getting-started#introduction"},"supported databases"),".")),(0,n.kt)("h5",{id:"documentation-sitemap"},"Documentation Sitemap"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/dependencies"},"Dependencies")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/supported-compilers"},"Supported Compilers")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/getting-started"},"Database"),(0,n.kt)("ul",{parentName:"li"},(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/getting-started"},"Getting Started")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/query-builder"},"Query Builder")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/migrations"},"Migrations")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/seeding"},"Seeding")))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/getting-started"},"TinyORM"),(0,n.kt)("ul",{parentName:"li"},(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/getting-started"},"Getting Started")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/relationships"},"Relationships")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/collections"},"Collections")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/casts"},"Casts")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/serialization"},"Serialization")))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/tinyorm"},"Building"),(0,n.kt)("ul",{parentName:"li"},(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/tinyorm"},"TinyORM")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/hello-world"},"Hello world")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/migrations"},"Migrations")))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/features-summary"},"Features Summary")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/sponsors"},"Sponsors"))),(0,n.kt)("h5",{id:"current-versions"},"Current versions"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"TinyORM")," v0.37.0"),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"tom")," v0.8.0"),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"TinyDrivers")," v0.1.0"),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"TinyMySql")," v0.1.0")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[67],{3905:(e,t,a)=>{a.d(t,{Zo:()=>m,kt:()=>y});var r=a(7294);function n(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function i(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,r)}return a}function o(e){for(var t=1;t=0||(n[a]=e[a]);return n}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(n[a]=e[a])}return n}var s=r.createContext({}),p=function(e){var t=r.useContext(s),a=t;return e&&(a="function"==typeof e?e(t):o(o({},t),e)),a},m=function(e){var t=p(e.components);return r.createElement(s.Provider,{value:t},e.children)},u="mdxType",d={inlineCode:"code",wrapper:function(e){var t=e.children;return r.createElement(r.Fragment,{},t)}},c=r.forwardRef((function(e,t){var a=e.components,n=e.mdxType,i=e.originalType,s=e.parentName,m=l(e,["components","mdxType","originalType","parentName"]),u=p(a),c=n,y=u["".concat(s,".").concat(c)]||u[c]||d[c]||i;return a?r.createElement(y,o(o({ref:t},m),{},{components:a})):r.createElement(y,o({ref:t},m))}));function y(e,t){var a=arguments,n=t&&t.mdxType;if("string"==typeof e||n){var i=a.length,o=new Array(i);o[0]=c;var l={};for(var s in t)hasOwnProperty.call(t,s)&&(l[s]=t[s]);l.originalType=e,l[u]="string"==typeof e?e:n,o[1]=l;for(var p=2;p{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var r=a(7462),n=(a(7294),a(3905));const i={sidebar_position:0,sidebar_label:"\ud83d\udd25 Prologue",slug:"/",hide_table_of_contents:!0,description:"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries. The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests.",keywords:["c++ orm","prologue","tinyorm"]},o="Prologue",l={unversionedId:"README",id:"README",title:"Prologue",description:"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries. The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests.",source:"@site/docs/README.mdx",sourceDirName:".",slug:"/",permalink:"/",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/README.mdx",tags:[],version:"current",sidebarPosition:0,frontMatter:{sidebar_position:0,sidebar_label:"\ud83d\udd25 Prologue",slug:"/",hide_table_of_contents:!0,description:"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries. The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests.",keywords:["c++ orm","prologue","tinyorm"]},sidebar:"tinyormSidebar",next:{title:"\ud83d\udd27 Dependencies",permalink:"/dependencies"}},s={},p=[{value:"Documentation Sitemap",id:"documentation-sitemap",level:5},{value:"Current versions",id:"current-versions",level:5}],m={toc:p},u="wrapper";function d(e){let{components:t,...a}=e;return(0,n.kt)(u,(0,r.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("h1",{id:"prologue"},"Prologue"),(0,n.kt)("p",null,"TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the ",(0,n.kt)("inlineCode",{parentName:"p"},"QtCore")," and ",(0,n.kt)("inlineCode",{parentName:"p"},"QtSql")," libraries."),(0,n.kt)("p",null,"The code is written in the modern C++20 way and is ",(0,n.kt)("strong",{parentName:"p"},"heavily")," tested with ",(0,n.kt)("strong",{parentName:"p"},"3366")," unit and functional tests. Almost all the query builder methods are unit tested. The TinyORM's query builder code and the code which is responsible for obtaining relationships, is tested by functional tests against all supported databases. The code coverage is good enough to guarantee API and behavior compatibility."),(0,n.kt)("admonition",{type:"tip"},(0,n.kt)("p",{parentName:"admonition"},"For a quick look at what's inside, check out the ",(0,n.kt)("a",{parentName:"p",href:"/features-summary"},"Features Summary"),".")),(0,n.kt)("admonition",{type:"info"},(0,n.kt)("p",{parentName:"admonition"},"If you don't want to use full ",(0,n.kt)("a",{parentName:"p",href:"/tinyorm/getting-started"},(0,n.kt)("inlineCode",{parentName:"a"},"ORM")),", then you can use only the ",(0,n.kt)("a",{parentName:"p",href:"/database/query-builder"},(0,n.kt)("inlineCode",{parentName:"a"},"Query Builder")),", which is outstanding. \ud83d\udd25 This way you can avoid writing raw SQL queries and your code will run on all ",(0,n.kt)("a",{parentName:"p",href:"/database/getting-started#introduction"},"supported databases"),".")),(0,n.kt)("h5",{id:"documentation-sitemap"},"Documentation Sitemap"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/dependencies"},"Dependencies")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/supported-compilers"},"Supported Compilers")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/getting-started"},"Database"),(0,n.kt)("ul",{parentName:"li"},(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/getting-started"},"Getting Started")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/query-builder"},"Query Builder")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/migrations"},"Migrations")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/database/seeding"},"Seeding")))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/getting-started"},"TinyORM"),(0,n.kt)("ul",{parentName:"li"},(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/getting-started"},"Getting Started")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/relationships"},"Relationships")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/collections"},"Collections")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/casts"},"Casts")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/tinyorm/serialization"},"Serialization")))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/tinyorm"},"Building"),(0,n.kt)("ul",{parentName:"li"},(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/tinyorm"},"TinyORM")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/hello-world"},"Hello world")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/building/migrations"},"Migrations")))),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/features-summary"},"Features Summary")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"/sponsors"},"Sponsors"))),(0,n.kt)("h5",{id:"current-versions"},"Current versions"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"TinyORM")," v0.37.1"),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"tom")," v0.9.0"),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"TinyDrivers")," v0.1.0"),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("strong",{parentName:"li"},"TinyMySql")," v0.1.0")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8a8faf8d.3f5122a9.js b/assets/js/8a8faf8d.2ff78836.js similarity index 99% rename from assets/js/8a8faf8d.3f5122a9.js rename to assets/js/8a8faf8d.2ff78836.js index 62b0fe493..87736ad51 100644 --- a/assets/js/8a8faf8d.3f5122a9.js +++ b/assets/js/8a8faf8d.2ff78836.js @@ -1 +1 @@ -"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[225],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),i=n(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>y});var a=n(7462),i=n(7294),o=n(6010),r=n(2466),l=n(6550),s=n(1980),p=n(7392),m=n(12);function d(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:i}}=e;return{value:t,label:n,attributes:a,default:i}}))}function u(e){const{values:t,children:n}=e;return(0,i.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function c(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function k(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function h(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=u(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!c({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,p]=k({queryString:n,groupId:a}),[d,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,m.Nk)(n);return[a,(0,i.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),g=(()=>{const e=s??d;return c({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!c({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),p(e),h(e)}),[p,h,o]),tabValues:o}}var g=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function N(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:p}=e;const m=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),u=e=>{const t=e.currentTarget,n=m.indexOf(t),a=p[n].value;a!==l&&(d(t),s(a))},c=e=>{let t=null;switch(e.key){case"Enter":u(e);break;case"ArrowRight":{const n=m.indexOf(e.currentTarget)+1;t=m[n]??m[0];break}case"ArrowLeft":{const n=m.indexOf(e.currentTarget)-1;t=m[n]??m[m.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:r}=e;return i.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>m.push(e),onKeyDown:c,onClick:u},r,{className:(0,o.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function f(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=h(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},i.createElement(N,(0,a.Z)({},e,t)),i.createElement(f,(0,a.Z)({},e,t)))}function y(e){const t=(0,g.Z)();return i.createElement(T,(0,a.Z)({key:String(t)},e))}},2044:(e,t,n)=>{n.d(t,{$t:()=>d,Ae:()=>g,C:()=>k,DK:()=>b,Fo:()=>l,Fs:()=>i,IM:()=>h,IZ:()=>a,RS:()=>C,VE:()=>N,Wg:()=>T,_A:()=>p,al:()=>_,jk:()=>c,js:()=>s,of:()=>m,q5:()=>r,qb:()=>y,vk:()=>u,wU:()=>o,zg:()=>f});const a="shell",i="database",o="application",r="bash",l="pwsh",s="zsh",p="maria",m="mysql",d="postgres",u="sqlite",c="application",k="bash",h="pwsh",g="zsh",b="MariaDB",N="MySQL",f="PostgreSQL",T="SQLite",y="tinyorm.org",_="$HOME/Code/c/",C="$env:USERPROFILE\\Code\\c\\"},4355:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),i=n(9482);function o(){const e=(0,a.useContext)(i.Z);if(null!=e)return e;throw new Error("useRootFolderContext is used outside of Layout component.")}},6005:(e,t,n)=>{n.d(t,{AE:()=>l,EA:()=>r,em:()=>p,go:()=>s,mT:()=>m,we:()=>d});var a=n(4355),i=n(2389),o=n(2044);const r=function(e,t){return void 0===t&&(t=!0),u((0,a.Z)().rootFolder[e]??p(e),e,t)},l=()=>(0,a.Z)().rootFolder[o.wU]??p(o.wU),s=function(e,t){if(void 0===t&&(t=!0),null==e)throw new Error("The groupId in the applicationFolderPath() can not be empty.");const n=t||e!==o.Fo?"/":"\\";return u(r(e)+n+l(),e,t)};function p(e){if(null==e)throw new Error("The groupId in the folderDefaultValue() can not be empty.");if(!(0,i.Z)())return"";switch(e){case o.Fo:return o.RS;case o.q5:return o.al;case o.wU:return o.qb;default:throw new Error(`No default value for '${e}' groupId in the folderDefaultValue().`)}}function m(e){return e===o.wU}function d(e,t){if(null==t||""===t)return t;const n="$ENV{$1}$2";switch(e){case o.Fo:return k(t).replace(/\$env:(.+?)(\/.*)/,n);case o.q5:return t.replace(/\$(.+?)(\/.*)/,n);default:throw new Error(`Unsupported shell type '${e}' in the convertToCmakeEnvVariable().`)}}function u(e,t,n){if(void 0===n&&(n=!0),null==e||""===e)return e;if(t!==o.Fo)return c(e);const a=c(e);return n?k(a):function(e){return null==e||""===e?e:e.replaceAll(/\/+/g,"\\")}(a)}function c(e){return null==e||""===e?e:e.replace(/[/\\]+$/,"")}function k(e){return null==e||""===e?e:e.replaceAll(/\\+(?! )/g,"/")}},3974:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>d,default:()=>b,frontMatter:()=>m,metadata:()=>u,toc:()=>k});var a=n(7462),i=(n(7294),n(3905)),o=n(7693),r=n(5162),l=n(4866),s=n(2044),p=n(6005);const m={sidebar_position:3,sidebar_label:"Migrations",description:"How to compile the TinyORM migrations (tom) C++ console application on Windows and Linux.",keywords:["c++ orm","building","migrations","tinyorm"]},d="Building: Migrations",u={unversionedId:"building/migrations",id:"building/migrations",title:"Building: Migrations",description:"How to compile the TinyORM migrations (tom) C++ console application on Windows and Linux.",source:"@site/docs/building/migrations.mdx",sourceDirName:"building",slug:"/building/migrations",permalink:"/building/migrations",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/building/migrations.mdx",tags:[],version:"current",sidebarPosition:3,frontMatter:{sidebar_position:3,sidebar_label:"Migrations",description:"How to compile the TinyORM migrations (tom) C++ console application on Windows and Linux.",keywords:["c++ orm","building","migrations","tinyorm"]},sidebar:"tinyormSidebar",previous:{title:"Hello world",permalink:"/building/hello-world"},next:{title:"\ud83d\udcc4 Features Summary",permalink:"/features-summary"}},c={},k=[{value:"Introduction",id:"introduction",level:2},{value:"Install dependencies",id:"install-dependencies",level:2},{value:"Using vcpkg.json (manifest mode)",id:"using-vcpkg-json-manifest-mode",level:4},{value:"Using vcpkg install (manually)",id:"using-vcpkg-install-manually",level:4},{value:"Source code",id:"source-code",level:2},{value:"Main file",id:"main-file",level:3},{value:"Migrations",id:"migrations",level:3},{value:"Seeders",id:"seeders",level:3},{value:"Migrations with CMake",id:"migrations-with-cmake",level:2},{value:"CMake project",id:"cmake-project",level:3},{value:"Build migrations",id:"build-migrations-cmake",level:3},{value:"Execute migrations",id:"execute-migrations-cmake",level:3},{value:"Migrations with qmake",id:"migrations-with-qmake",level:2},{value:"qmake project",id:"qmake-project",level:3},{value:"Auto-configure using .qmake.conf and .env",id:"auto-configure-using-qmakeconf-and-env",level:4},{value:"Migrations source files",id:"migrations-source-files",level:4},{value:"Seeders source files",id:"seeders-source-files",level:4},{value:"Build migrations",id:"build-migrations-qmake",level:3},{value:"Execute migrations",id:"execute-migrations-qmake",level:3},{value:"Finish",id:"finish",level:2}],h={toc:k},g="wrapper";function b(e){let{components:t,...m}=e;return(0,i.kt)(g,(0,a.Z)({},h,m,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"building-migrations"},"Building: Migrations"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#introduction"},"Introduction")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#install-dependencies"},"Install dependencies"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#using-vcpkg-json-manifest-mode"},"Using vcpkg.json")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#using-vcpkg-install-manually"},"Using vcpkg install")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#source-code"},"Source code"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#main-file"},"Main file")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#migrations"},"Migrations")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#seeders"},"Seeders")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#migrations-with-cmake"},"Migrations with CMake"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#cmake-project"},"CMake project")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#build-migrations-cmake"},"Build migrations")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#execute-migrations-cmake"},"Execute migrations")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#migrations-with-qmake"},"Migrations with qmake"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#qmake-project"},"qmake project")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#build-migrations-qmake"},"Build migrations")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#execute-migrations-qmake"},"Execute migrations")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#finish"},"Finish"))),(0,i.kt)("h2",{id:"introduction"},"Introduction"),(0,i.kt)("p",null,"We will try to create a working migrations console application called as ",(0,i.kt)("abbr",{title:"TinyORM migrations"},(0,i.kt)("inlineCode",{parentName:"p"},"tom"))," in the terminal with the ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," and in the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," with the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build systems."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," console application also expects the following ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure"),", let's create them."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.Fo)}\nmkdir tom/tom\ncd tom`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.q5)}\nmkdir -p tom/tom\ncd tom`))),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source tree contains the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," example application, you can inspire or look at the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/examples/tom"},"source code"),". Also, ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," unit tests use a ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," migrations internally to create the database structure, internally called as the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/tests/testdata_tom"},(0,i.kt)("inlineCode",{parentName:"a"},"tom")," migrations for unit tests"),"."),(0,i.kt)("p",null,"All these three console applications the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," example, ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," migrations for unit tests, and the application described in this tutorial have practically identical source code (the main.cpp file)."),(0,i.kt)("admonition",{type:"note"},(0,i.kt)("p",{parentName:"admonition"},"The ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," is able to generate ",(0,i.kt)("a",{href:"https://en.wikipedia.org/wiki/Data_definition_language",title:"Data Definition Language"},"DDL")," queries for all the ",(0,i.kt)("a",{parentName:"p",href:"/database/getting-started#introduction"},"supported databases")," databases.")),(0,i.kt)("admonition",{type:"info"},(0,i.kt)("p",{parentName:"admonition"},"You can see the ",(0,i.kt)("a",{parentName:"p",href:"/features-summary#tom-console-application"},"Tom showcase image")," of how the resulting ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," console application will look like.")),(0,i.kt)("h2",{id:"install-dependencies"},"Install dependencies"),(0,i.kt)("p",null,"First, install the ",(0,i.kt)("inlineCode",{parentName:"p"},"vcpkg")," package manager as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#vcpkg"},"here"),"."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries are required dependencies because ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," uses them in header files, you have to install them before you can use ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM"),". The ",(0,i.kt)("inlineCode",{parentName:"p"},"tabulate")," library is only needed in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," migrations it's used by the ",(0,i.kt)("inlineCode",{parentName:"p"},"migrate:status")," command."),(0,i.kt)("p",null,"There are two ways how to install the ",(0,i.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries using ",(0,i.kt)("inlineCode",{parentName:"p"},"vcpkg"),"."),(0,i.kt)("p",null,"Also, don't forget to build the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," library with the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," source code enabled (it's enabled by default) as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm"},"here"),"."),(0,i.kt)("h4",{id:"using-vcpkg-json-manifest-mode"},"Using vcpkg.json ",(0,i.kt)("small",null,"(manifest mode)")),(0,i.kt)("p",null,"Create a ",(0,i.kt)("inlineCode",{parentName:"p"},"vcpkg.json")," file with the following content. ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," example below uses this method."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd tom\nvim vcpkg.json\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json",metastring:"title='vcpkg.json'",title:"'vcpkg.json'"},'{\n "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",\n "name": "tom",\n "version-semver": "0.1.0",\n "description": "Tom console application for TinyORM C++ library",\n "homepage": "https://github.com/silverqx/TinyORM",\n "documentation": "https://www.tinyorm.org/building/migrations",\n "maintainers": "Silver Zachara ",\n "supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",\n "dependencies": [\n "range-v3",\n "tabulate"\n ]\n}\n')),(0,i.kt)("admonition",{type:"note"},(0,i.kt)("p",{parentName:"admonition"},"Only ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," via the ",(0,i.kt)("inlineCode",{parentName:"p"},"toolchain file")," supports this method.")),(0,i.kt)("h4",{id:"using-vcpkg-install-manually"},"Using vcpkg install ",(0,i.kt)("small",null,"(manually)")),(0,i.kt)("p",null,"This method can be used with both ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../../vcpkg\n\nvcpkg search range-v3\nvcpkg search tabulate\nvcpkg install range-v3 tabulate\nvcpkg list\n")),(0,i.kt)("h2",{id:"source-code"},"Source code"),(0,i.kt)("p",null,"Let's start in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," project folder."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.Fo)}/tom/tom`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.q5)}/tom/tom`))),(0,i.kt)("h3",{id:"main-file"},"Main file"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"main.cpp")," source file."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"vim main.cpp\n")),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,i.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,i.kt)("kbd",null,"Shift")," + ",(0,i.kt)("kbd",null,"p"),".")),(0,i.kt)("p",null,"And paste the following code."),(0,i.kt)("a",{id:"string-constants-example"}),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='main.cpp'",title:"'main.cpp'"},'#include \n\n#include \n\n#include "migrations/2014_10_12_000000_create_posts_table.hpp"\n\n#include "seeders/databaseseeder.hpp"\n\nusing Orm::DatabaseManager;\nusing Orm::DB;\n\nusing TomApplication = Tom::Application;\n\nusing namespace Migrations; // NOLINT(google-build-using-namespace)\nusing namespace Seeders; // NOLINT(google-build-using-namespace)\n\n/*! Create the database manager instance and add a database connection. */\nstd::shared_ptr setupDatabaseManager();\n\n/*! C++ main function. */\nint main(int argc, char *argv[])\n{\n try {\n // Ownership of the shared_ptr()\n auto db = setupDatabaseManager();\n\n return TomApplication(argc, argv, std::move(db), "TOM_EXAMPLE_ENV")\n .migrations()\n .seeders()\n // Fire it up \ud83d\udd25\ud83d\ude80\u2728\n .run();\n\n } catch (const std::exception &e) {\n\n TomApplication::logException(e);\n }\n\n return EXIT_FAILURE;\n}\n\nstd::shared_ptr setupDatabaseManager()\n{\n using namespace Orm::Constants; // NOLINT(google-build-using-namespace)\n\n // Ownership of the shared_ptr()\n return DB::create({\n {driver_, QMYSQL},\n {host_, qEnvironmentVariable("DB_MYSQL_HOST", H127001)},\n {port_, qEnvironmentVariable("DB_MYSQL_PORT", P3306)},\n {database_, qEnvironmentVariable("DB_MYSQL_DATABASE", EMPTY)},\n {username_, qEnvironmentVariable("DB_MYSQL_USERNAME", EMPTY)},\n {password_, qEnvironmentVariable("DB_MYSQL_PASSWORD", EMPTY)},\n {charset_, qEnvironmentVariable("DB_MYSQL_CHARSET", UTF8MB4)},\n {collation_, qEnvironmentVariable("DB_MYSQL_COLLATION", UTF8MB40900aici)},\n {timezone_, TZ00},\n /* Specifies what time zone all QDateTime-s will have, the overridden default is\n the Qt::UTC, set to the Qt::LocalTime or QtTimeZoneType::DontConvert to use\n the system local time. */\n {qt_timezone, QVariant::fromValue(Qt::UTC)},\n {strict_, true},\n },\n QStringLiteral("tinyorm_tom_mysql")); // shell:connection\n}\n')),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"If you have defined more database connections then you can tag the lines with the database connection names with the ",(0,i.kt)("inlineCode",{parentName:"p"},"// shell:connection")," comment and this connection names will be provided to the bash, zsh, pwsh completions for the ",(0,i.kt)("inlineCode",{parentName:"p"},"--database=")," option \ud83d\ude0e, ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/examples/tom/main.cpp#L74"},"example"),".")),(0,i.kt)("h3",{id:"migrations"},"Migrations"),(0,i.kt)("p",null,"If you have already built the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application then you can generate a migrations using the ",(0,i.kt)("a",{parentName:"p",href:"/database/migrations#generating-migrations"},(0,i.kt)("inlineCode",{parentName:"a"},"make:migration"))," command \ud83d\ude0e."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"tom make:migration create_posts_table\n")),(0,i.kt)("p",null,"Below is the expected folders structure for the migrations. The ",(0,i.kt)("a",{parentName:"p",href:"#migrations-source-files"},(0,i.kt)("inlineCode",{parentName:"a"},"migrations.pri"))," file is used only by the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build system and is not needed with ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," builds."),(0,i.kt)("a",{id:"folders-structure"}),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-text"},"tom/\n\u2514\u2500\u2500 database/\n \u251c\u2500\u2500 migrations/\n \u251c\u2500\u2500 seeders/\n \u251c\u2500\u2500 migrations.pri\n \u2514\u2500\u2500 seeders.pri\n")),(0,i.kt)("p",null,"Let's create the first migration manually."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"mkdir database/migrations\n\nvim database/migrations/2014_10_12_000000_create_posts_table.hpp")),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"mkdir -p database/migrations\n\nvim database/migrations/2014_10_12_000000_create_posts_table.hpp"))),(0,i.kt)("p",null,"And paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='database/migrations/2014_10_12_000000_create_posts_table.hpp'",title:"'database/migrations/2014_10_12_000000_create_posts_table.hpp'"},'#pragma once\n\n#include \n\nnamespace Migrations\n{\n\n struct CreatePostsTable : Migration\n {\n /*! Filename of the migration file. */\n T_MIGRATION\n\n /*! Run the migrations. */\n void up() const override\n {\n Schema::create("posts", [](Blueprint &table)\n {\n table.id();\n\n table.string(NAME);\n table.timestamps();\n });\n }\n\n /*! Reverse the migrations. */\n void down() const override\n {\n Schema::dropIfExists("posts");\n }\n };\n\n} // namespace Migrations\n')),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"The ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source tree contains the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/tests/database/migrations/2014_10_12_000000_create_posts_table.hpp#L5"},(0,i.kt)("inlineCode",{parentName:"a"},"CreatePostsTable"))," example migration that also acts as the full-fledged example migration. It has defined and also nicely commented all possible features that migration classes can use or define.")),(0,i.kt)("admonition",{type:"info"},(0,i.kt)("p",{parentName:"admonition"},"If you want, you can also build the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application without the migrations, simply comment out the ",(0,i.kt)("inlineCode",{parentName:"p"},"migrations")," method and the corresponding ",(0,i.kt)("inlineCode",{parentName:"p"},'#include "migrations/xyz.hpp"')," files.")),(0,i.kt)("h3",{id:"seeders"},"Seeders"),(0,i.kt)("p",null,"If you have already built the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application then you can generate a seeder using the ",(0,i.kt)("a",{parentName:"p",href:"/database/seeding#writing-seeders"},(0,i.kt)("inlineCode",{parentName:"a"},"make:seeder"))," command \ud83d\ude0e."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"tom make:seeder PostSeeder\n")),(0,i.kt)("p",null,"The expected folders structure is described a few paragraphs ",(0,i.kt)("a",{parentName:"p",href:"#folders-structure"},"above"),". The ",(0,i.kt)("a",{parentName:"p",href:"#seeders-source-files"},(0,i.kt)("inlineCode",{parentName:"a"},"seeders.pri"))," file is used only by the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build system and is not needed with ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," builds."),(0,i.kt)("p",null,"Let's create the root seeder class manually."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"mkdir database/seeders\n\nvim database/seeders/databaseseeder.hpp")),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"mkdir -p database/seeders\n\nvim database/seeders/databaseseeder.hpp"))),(0,i.kt)("p",null,"And paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='database/seeders/databaseseeder.hpp'",title:"'database/seeders/databaseseeder.hpp'"},'#pragma once\n\n#include \n\nnamespace Seeders\n{\n\n /*! Main database seeder. */\n struct DatabaseSeeder : Seeder\n {\n /*! Run the database seeders. */\n void run() override\n {\n DB::table("posts")->insert({\n {{"name", "1. post"}},\n {{"name", "2. post"}},\n });\n }\n };\n\n} // namespace Seeders\n')),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"The ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source tree contains the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/tests/database/seeders/databaseseeder.hpp#L8"},(0,i.kt)("inlineCode",{parentName:"a"},"DatabaseSeeder"))," root seeder example class that also acts as the full-fledged example seeder. It has defined and also nicely commented all possible features that seeder classes can use or define.")),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"You can create more seeder classes like this and use the ",(0,i.kt)("inlineCode",{parentName:"p"},"call<>()")," method to invoke them as is described in the ",(0,i.kt)("a",{parentName:"p",href:"/database/seeding#calling-additional-seeders"},"Calling Additional Seeders")," section.")),(0,i.kt)("h2",{id:"migrations-with-cmake"},"Migrations with CMake"),(0,i.kt)("p",null,"Create a folder for the ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," build."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"cd ..\nmkdir tom-builds-cmake/build-debug\n\ncd tom")),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"cd ..\nmkdir -p tom-builds-cmake/build-debug\n\ncd tom"))),(0,i.kt)("h3",{id:"cmake-project"},"CMake project"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file with the following content. I leave the comments in the ",(0,i.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file because it's not as simple as the ",(0,i.kt)("inlineCode",{parentName:"p"},"Hello world")," example; to make it clear what's going on."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cmake",metastring:"title='CMakeLists.txt'",title:"'CMakeLists.txt'"},'cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\n# Specify the C++ standard\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\n# Initialize variables\n# ---\n\nset(Tom_ns tom)\nset(Tom_target tom)\n\nfile(REAL_PATH "../../TinyORM" TinyMainDir)\n\nset(TinyOrmSourceDir "${TinyMainDir}/TinyORM")\nset(TinyOrmBuildDir "${TinyMainDir}/TinyORM-builds-cmake/build-debug")\n\n# TinyORM CMake modules (needed to set the executable version and RC file on Windows)\nlist(APPEND CMAKE_MODULE_PATH "${TinyOrmSourceDir}/cmake/CommonModules")\n\n# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${TinyOrmBuildDir}")\n\n# Initialize Project Version\n# ---\n\ninclude(TinyHelpers)\ntiny_read_version(TINY_VERSION\n TINY_VERSION_MAJOR TINY_VERSION_MINOR TINY_VERSION_PATCH TINY_VERSION_TWEAK\n VERSION_HEADER "${TinyOrmSourceDir}/tom/include/tom/version.hpp"\n PREFIX TINYTOM\n HEADER_FOR "${Tom_ns}"\n)\n\n# Basic project\n# ---\n\nproject(${Tom_ns}\n DESCRIPTION "Tom console application for TinyORM C++ library"\n HOMEPAGE_URL "https://www.tinyorm.org"\n LANGUAGES CXX\n VERSION ${TINY_VERSION}\n)\n\n# Tom command-line application\n# ---\n\nadd_executable(${Tom_target}\n main.cpp\n)\nadd_executable(${Tom_ns}::${Tom_target} ALIAS ${Tom_target})\n\n# Tom command-line application specific configuration\n# ---\n\nset_target_properties(${Tom_target}\n PROPERTIES\n C_VISIBILITY_PRESET "hidden"\n CXX_VISIBILITY_PRESET "hidden"\n VISIBILITY_INLINES_HIDDEN YES\n VERSION ${PROJECT_VERSION}\n)\n\ntarget_include_directories(${Tom_target}\n PRIVATE "$"\n)\n\n# Tom command-line application defines\n# ---\n\ntarget_compile_definitions(${Tom_target}\n PRIVATE\n PROJECT_TOM\n)\n\n# Windows resource and manifest files\n# ---\n\n# Find icons, tom/version.hpp, and Windows manifest file for MinGW\nif(CMAKE_SYSTEM_NAME STREQUAL "Windows")\n tiny_set_rc_flags("-I \\"${TinyOrmSourceDir}/tom/resources\\"")\nendif()\n\ninclude(TinyResourceAndManifest)\ntiny_resource_and_manifest(${Tom_target}\n OUTPUT_DIR "${TINY_BUILD_GENDIR}/tmp/"\n RESOURCES_DIR "${TinyOrmSourceDir}/tom/resources"\n)\n\n# Resolve and link dependencies\n# ---\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.0 CONFIG REQUIRED)\n\n# Unconditional dependencies\ntarget_link_libraries(${Tom_target}\n PRIVATE\n Qt${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)\n')),(0,i.kt)("h3",{id:"build-migrations-cmake"},"Build migrations"),(0,i.kt)("p",null,"Now you are ready to configure ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," application. Don't forget to prepare the build environment with the ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#windows-prerequisites"},(0,i.kt)("inlineCode",{parentName:"a"},"qtenv6.ps1"))," command if you are building with the ",(0,i.kt)("inlineCode",{parentName:"p"},"msvc"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../tom-builds-cmake/build-debug\n")),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cmake.exe \`\n-S "${(0,p.go)(s.Fo)}/tom/tom" \`\n-B "${(0,p.go)(s.Fo)}/tom/tom-builds-cmake/build-debug" \`\n-G 'Ninja' \`\n-D CMAKE_BUILD_TYPE:STRING='Debug' \`\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(s.Fo)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \`\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(s.Fo)}/tmp/tom"`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cmake \\\n-S "${(0,p.go)(s.q5)}/tom/tom" \\\n-B "${(0,p.go)(s.q5)}/tom/tom-builds-cmake/build-debug" \\\n-G 'Ninja' \\\n-D CMAKE_BUILD_TYPE:STRING='Debug' \\\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(s.q5)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \\\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(s.q5)}/tmp/tom"`))),(0,i.kt)("p",null,"And build."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target all\n")),(0,i.kt)("h3",{id:"execute-migrations-cmake"},"Execute migrations"),(0,i.kt)("p",null,"Do not forget to add ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyOrm0d.dll")," on the path on Windows and on the ",(0,i.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application can find it during execution, as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#tinyorm-on-path-cmake"},"here"),"."),(0,i.kt)(l.Z,{groupId:s.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,p.go)(s.Fo,!1)}\\TinyORM\\TinyORM-builds-cmake\\build-debug;" + $env:Path`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,p.go)(s.q5)}/TinyORM/TinyORM-builds-cmake/build-debug\${PATH:+:}$PATH`))),(0,i.kt)("p",null,"Execute ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-powershell"},".\\tom.exe migrate:status\n"))),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"./tom migrate:status\n")))),(0,i.kt)("p",null,"The output will look something like this."),(0,i.kt)("img",{src:n(3086).Z,alt:"Tom migrations - migrate:status command output",width:"660"}),(0,i.kt)("p",null,"See also the ",(0,i.kt)("a",{parentName:"p",href:"#finish"},"final thoughts")," on how to verify the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," executable file properties."),(0,i.kt)("p",null,"Happy migrating \ud83c\udf89\ud83d\udc4c"),(0,i.kt)("h2",{id:"migrations-with-qmake"},"Migrations with qmake"),(0,i.kt)("p",null,"Create a folder for the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.Fo)}/tom\n\nmkdir tom-builds-qmake`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.q5)}/tom\n\nmkdir tom-builds-qmake`))),(0,i.kt)("p",null,"The ",(0,i.kt)("a",{parentName:"p",href:"#source-code"},(0,i.kt)("inlineCode",{parentName:"a"},"source code"))," is the same as for the ",(0,i.kt)("inlineCode",{parentName:"p"},"Migrations with CMake")," console application."),(0,i.kt)("h3",{id:"qmake-project"},"qmake project"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"tom.pro")," qmake file with the following content."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd tom\nvim tom.pro\n")),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,i.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,i.kt)("kbd",null,"Shift")," + ",(0,i.kt)("kbd",null,"p"),".")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='tom.pro'",title:"'tom.pro'"},"QT -= gui\n\nTEMPLATE = app\nTARGET = tom\n\nCONFIG *= cmdline\n\nDEFINES *= PROJECT_TOM\n\nSOURCES += $$PWD/main.cpp\n\n# Database migrations\ninclude($$PWD/database/migrations.pri)\n# Database seeders\ninclude($$PWD/database/seeders.pri)\n\n# Auto-configure TinyORM library for the migrations purposes \ud83d\udd25\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/tom.pri)\n")),(0,i.kt)("admonition",{type:"caution"},(0,i.kt)("p",{parentName:"admonition"},"The exact ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," is crucial in this example because the paths to the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source and build folders are relative.")),(0,i.kt)("admonition",{type:"caution"},(0,i.kt)("p",{parentName:"admonition"},"Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!")),(0,i.kt)("h4",{id:"auto-configure-using-qmakeconf-and-env"},(0,i.kt)("inlineCode",{parentName:"h4"},"Auto-configure")," using ",(0,i.kt)("inlineCode",{parentName:"h4"},".qmake.conf")," and ",(0,i.kt)("inlineCode",{parentName:"h4"},".env")),(0,i.kt)("p",null,"If you want to have properly configured ",(0,i.kt)("inlineCode",{parentName:"p"},"DEFINES")," (C preprocessor macros), have Qt headers marked as system headers, or eg. have properly set properties of an executable file such as version and description, then you need to specify a path to the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," qmake features (",(0,i.kt)("inlineCode",{parentName:"p"},".prf")," files) which handle this correctly; this path is provided by the ",(0,i.kt)("inlineCode",{parentName:"p"},"QMAKEFEATURES")," variable and can only be set in the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"Read the ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#consume-tinyorm-library-qmake"},"Consume TinyOrm library (qmake)")," section, as everything that is described in that section applies here as well.")),(0,i.kt)("p",null,"Create the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application root folder with the following content."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the PARENT folder of the TinyORM source folder\nTINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)\n# To find .env and .env.$$QMAKE_PLATFORM files\nTINY_DOTENV_ROOT = $$PWD\n# Path to the current build tree (used to guess the TinyORM build tree)\n#TINY_BUILD_TREE = $$shadowed($$PWD)\n\n# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants\nQMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)\n")),(0,i.kt)("p",null,"Then, create a ",(0,i.kt)("code",null,".env.(win32","|","unix","|","mingw)")," file in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application root folder with the following content."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:".env.win32",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in the tom.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)\n\n# Path to the vcpkg - range-v3 and tabulate\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-windows\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n"))),(0,i.kt)(r.Z,{value:s.q5,label:".env.unix",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in the tom.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_clang16_64bit_ccache-Debug/)\n\n# Path to the vcpkg - range-v3 and tabulate\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-linux\n\n# Use faster linker\nclang: CONFIG *= use_lld_linker\nelse: CONFIG *= use_gold_linker\n\n# Or use the mold linker\n#QMAKE_LFLAGS *= -fuse-ld=mold\n"))),(0,i.kt)(r.Z,{value:"mingw",label:".env.mingw",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in the tom.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSYS2_UCRT64_clang_64bit-Debug/)\n\n# Path to the vcpkg - range-v3 and tabulate\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-mingw-dynamic\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n\n# Use faster linker (for both GCC and Clang)\n# CONFIG *= use_lld_linker does not work on MinGW\nQMAKE_LFLAGS *= -fuse-ld=lld\n")))),(0,i.kt)("p",null,"Don't forget to update the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"TINY_VCPKG_ROOT")," folder paths to your needs if you are not using the recommended ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},(0,i.kt)("inlineCode",{parentName:"a"},"Folders structure")),"."),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,i.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," if you don't like to specify it manually. Just comment out the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and uncomment the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINY_BUILD_TREE = $$shadowed($$PWD)")," in the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"You can entirely avoid the ",(0,i.kt)("inlineCode",{parentName:"p"},".env")," files, just move the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," to the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," or remove it by help of ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,i.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," and set the ",(0,i.kt)("inlineCode",{parentName:"p"},"VCPKG_ROOT")," environment variable at system level as is described in ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#set-up-vcpkg-environment"},(0,i.kt)("inlineCode",{parentName:"a"},"Set up vcpkg environment")),".")),(0,i.kt)("admonition",{type:"info"},(0,i.kt)("p",{parentName:"admonition"},"Configuring by the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," and ",(0,i.kt)("inlineCode",{parentName:"p"},".env")," files has one big advantage, which is that you don't have to modify the project files.")),(0,i.kt)("h4",{id:"migrations-source-files"},"Migrations source files"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"database/migrations.pri")," file and paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='database/migrations.pri'",title:"'database/migrations.pri'"},"INCLUDEPATH *= $$PWD\n\nHEADERS += \\\n $$PWD/migrations/2014_10_12_000000_create_posts_table.hpp \\\n")),(0,i.kt)("h4",{id:"seeders-source-files"},"Seeders source files"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"database/seeders.pri")," file and paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='database/seeders.pri'",title:"'database/seeders.pri'"},"INCLUDEPATH *= $$PWD\n\nHEADERS += \\\n $$PWD/seeders/databaseseeder.hpp \\\n")),(0,i.kt)("h3",{id:"build-migrations-qmake"},"Build migrations"),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"I recommend creating a new ",(0,i.kt)("inlineCode",{parentName:"p"},"Session")," in the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#open-qtcreator-ide"},"here"),".")),(0,i.kt)("p",null,"Now you can open the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom.pro")," project in the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),"."),(0,i.kt)("p",null,"This will open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Configure Project")," tab, select some kit and update build folder paths to meet our ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," or like you want."),(0,i.kt)("img",{src:n(6191).Z,alt:"tom - QtCreator - Configure Project",width:"760"}),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"You can force the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#qtcreator-default-build-directory"},"here"),".")),(0,i.kt)("p",null,"You are ready to configure build options, hit ",(0,i.kt)("kbd",null,"Ctrl"),"+",(0,i.kt)("kbd",null,"5")," to open ",(0,i.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,i.kt)("inlineCode",{parentName:"p"},"Build")," in the left sidebar to open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Build Settings"),", it should look similar to the following picture."),(0,i.kt)("img",{src:n(5539).Z,className:"no-blurry",alt:"tom - QtCreator - Build Settings",width:"760"}),(0,i.kt)("p",null,"Disable ",(0,i.kt)("inlineCode",{parentName:"p"},"QML debugging and profiling")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"Qt Quick Compiler"),", they are not used."),(0,i.kt)("p",null,"In the left sidebar open ",(0,i.kt)("inlineCode",{parentName:"p"},"Dependencies")," and check ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," project and ",(0,i.kt)("inlineCode",{parentName:"p"},"Synchronize configuration"),", this setting ensures that the current project will be rebuilt correctly when the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," library source code changes."),(0,i.kt)("p",null,"Everything is ready to build, you can press ",(0,i.kt)("kbd",null,"Ctrl"),"+",(0,i.kt)("kbd",null,"b")," to build the project."),(0,i.kt)("h3",{id:"execute-migrations-qmake"},"Execute migrations"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator")," takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the ",(0,i.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux."),(0,i.kt)("p",null,"The only thing you might want to change is to run the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application in the new terminal window. To do so, hit ",(0,i.kt)("kbd",null,"Ctrl"),"+",(0,i.kt)("kbd",null,"5")," to open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,i.kt)("inlineCode",{parentName:"p"},"Run")," in the left sidebar to open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Run Settings"),", then in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Run")," section select the ",(0,i.kt)("inlineCode",{parentName:"p"},"Run in terminal")," checkbox."),(0,i.kt)("p",null,"You can also set the ",(0,i.kt)("inlineCode",{parentName:"p"},"Command line arguments")," in this ",(0,i.kt)("inlineCode",{parentName:"p"},"Run")," section, eg. the ",(0,i.kt)("inlineCode",{parentName:"p"},"migrate:status"),"."),(0,i.kt)("p",null,"To execute the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application press ",(0,i.kt)("kbd",null,"Ctrl")," + ",(0,i.kt)("kbd",null,"r"),"."),(0,i.kt)("p",null,"The output will look ",(0,i.kt)("strong",{parentName:"p"},"very similar")," to this if you add more migrations."),(0,i.kt)("img",{src:n(3086).Z,alt:"Tom migrations - migrate:status command output",width:"660"}),(0,i.kt)("p",null,"Happy migrating \ud83c\udf89\ud83d\udc4c"),(0,i.kt)("h2",{id:"finish"},"Finish"),(0,i.kt)("p",null,"As the last thing, you can check that all the file properties were correctly set by the ",(0,i.kt)("a",{parentName:"p",href:"https://docs.microsoft.com/en-us/windows/win32/menurc/resource-compiler"},(0,i.kt)("inlineCode",{parentName:"a"},"rc"))," compiler."),(0,i.kt)("p",null,"Find the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom.exe")," file and press ",(0,i.kt)("kbd",null,"Alt")," + ",(0,i.kt)("kbd",null,"Enter")," to open the file properties. To check the executable manifest you can use eg. the ",(0,i.kt)("a",{parentName:"p",href:"http://www.angusj.com/resourcehacker/"},"Resource Hacker"),"."),(0,i.kt)("img",{src:n(643).Z,alt:"tom.exe file properties detail",width:"440"}))}b.isMDXComponent=!0},5539:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-build_settings-e10927d1c4ed852620f9eb7564198940.png"},6191:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-configure_project-4721257090370204b0272d166512adef.png"},643:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/tom_file_properties-0df513c47ceadd5c09165e41c6b53086.png"},3086:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/tom_migrate_status-63c129a10bfe6bffe8d2d5ea280860e5.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[225],{5162:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(7294),i=n(6010);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:t,hidden:n,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,i.Z)(o.tabItem,r),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>y});var a=n(7462),i=n(7294),o=n(6010),r=n(2466),l=n(6550),s=n(1980),p=n(7392),m=n(12);function d(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:i}}=e;return{value:t,label:n,attributes:a,default:i}}))}function u(e){const{values:t,children:n}=e;return(0,i.useMemo)((()=>{const e=t??d(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function c(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function k(e){let{queryString:t=!1,groupId:n}=e;const a=(0,l.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,i.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function h(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=u(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!c({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[s,p]=k({queryString:n,groupId:a}),[d,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,m.Nk)(n);return[a,(0,i.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),g=(()=>{const e=s??d;return c({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!c({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),p(e),h(e)}),[p,h,o]),tabValues:o}}var g=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function N(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:p}=e;const m=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.o5)(),u=e=>{const t=e.currentTarget,n=m.indexOf(t),a=p[n].value;a!==l&&(d(t),s(a))},c=e=>{let t=null;switch(e.key){case"Enter":u(e);break;case"ArrowRight":{const n=m.indexOf(e.currentTarget)+1;t=m[n]??m[0];break}case"ArrowLeft":{const n=m.indexOf(e.currentTarget)-1;t=m[n]??m[m.length-1];break}}t?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:r}=e;return i.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>m.push(e),onKeyDown:c,onClick:u},r,{className:(0,o.Z)("tabs__item",b.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function f(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,i.cloneElement)(e,{className:"margin-top--md"}):null}return i.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,i.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function T(e){const t=h(e);return i.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},i.createElement(N,(0,a.Z)({},e,t)),i.createElement(f,(0,a.Z)({},e,t)))}function y(e){const t=(0,g.Z)();return i.createElement(T,(0,a.Z)({key:String(t)},e))}},2044:(e,t,n)=>{n.d(t,{$t:()=>d,Ae:()=>g,C:()=>k,DK:()=>b,Fo:()=>l,Fs:()=>i,IM:()=>h,IZ:()=>a,RS:()=>C,VE:()=>N,Wg:()=>T,_A:()=>p,al:()=>_,jk:()=>c,js:()=>s,of:()=>m,q5:()=>r,qb:()=>y,vk:()=>u,wU:()=>o,zg:()=>f});const a="shell",i="database",o="application",r="bash",l="pwsh",s="zsh",p="maria",m="mysql",d="postgres",u="sqlite",c="application",k="bash",h="pwsh",g="zsh",b="MariaDB",N="MySQL",f="PostgreSQL",T="SQLite",y="tinyorm.org",_="$HOME/Code/c/",C="$env:USERPROFILE\\Code\\c\\"},4355:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),i=n(9482);function o(){const e=(0,a.useContext)(i.Z);if(null!=e)return e;throw new Error("useRootFolderContext is used outside of Layout component.")}},6005:(e,t,n)=>{n.d(t,{AE:()=>l,EA:()=>r,em:()=>p,go:()=>s,mT:()=>m,we:()=>d});var a=n(4355),i=n(2389),o=n(2044);const r=function(e,t){return void 0===t&&(t=!0),u((0,a.Z)().rootFolder[e]??p(e),e,t)},l=()=>(0,a.Z)().rootFolder[o.wU]??p(o.wU),s=function(e,t){if(void 0===t&&(t=!0),null==e)throw new Error("The groupId in the applicationFolderPath() can not be empty.");const n=t||e!==o.Fo?"/":"\\";return u(r(e)+n+l(),e,t)};function p(e){if(null==e)throw new Error("The groupId in the folderDefaultValue() can not be empty.");if(!(0,i.Z)())return"";switch(e){case o.Fo:return o.RS;case o.q5:return o.al;case o.wU:return o.qb;default:throw new Error(`No default value for '${e}' groupId in the folderDefaultValue().`)}}function m(e){return e===o.wU}function d(e,t){if(null==t||""===t)return t;const n="$ENV{$1}$2";switch(e){case o.Fo:return k(t).replace(/\$env:(.+?)(\/.*)/,n);case o.q5:return t.replace(/\$(.+?)(\/.*)/,n);default:throw new Error(`Unsupported shell type '${e}' in the convertToCmakeEnvVariable().`)}}function u(e,t,n){if(void 0===n&&(n=!0),null==e||""===e)return e;if(t!==o.Fo)return c(e);const a=c(e);return n?k(a):function(e){return null==e||""===e?e:e.replaceAll(/\/+/g,"\\")}(a)}function c(e){return null==e||""===e?e:e.replace(/[/\\]+$/,"")}function k(e){return null==e||""===e?e:e.replaceAll(/\\+(?! )/g,"/")}},3974:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>d,default:()=>b,frontMatter:()=>m,metadata:()=>u,toc:()=>k});var a=n(7462),i=(n(7294),n(3905)),o=n(7693),r=n(5162),l=n(4866),s=n(2044),p=n(6005);const m={sidebar_position:3,sidebar_label:"Migrations",description:"How to compile the TinyORM migrations (tom) C++ console application on Windows and Linux.",keywords:["c++ orm","building","migrations","tinyorm"]},d="Building: Migrations",u={unversionedId:"building/migrations",id:"building/migrations",title:"Building: Migrations",description:"How to compile the TinyORM migrations (tom) C++ console application on Windows and Linux.",source:"@site/docs/building/migrations.mdx",sourceDirName:"building",slug:"/building/migrations",permalink:"/building/migrations",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/building/migrations.mdx",tags:[],version:"current",sidebarPosition:3,frontMatter:{sidebar_position:3,sidebar_label:"Migrations",description:"How to compile the TinyORM migrations (tom) C++ console application on Windows and Linux.",keywords:["c++ orm","building","migrations","tinyorm"]},sidebar:"tinyormSidebar",previous:{title:"Hello world",permalink:"/building/hello-world"},next:{title:"\ud83d\udcc4 Features Summary",permalink:"/features-summary"}},c={},k=[{value:"Introduction",id:"introduction",level:2},{value:"Install dependencies",id:"install-dependencies",level:2},{value:"Using vcpkg.json (manifest mode)",id:"using-vcpkg-json-manifest-mode",level:4},{value:"Using vcpkg install (manually)",id:"using-vcpkg-install-manually",level:4},{value:"Source code",id:"source-code",level:2},{value:"Main file",id:"main-file",level:3},{value:"Migrations",id:"migrations",level:3},{value:"Seeders",id:"seeders",level:3},{value:"Migrations with CMake",id:"migrations-with-cmake",level:2},{value:"CMake project",id:"cmake-project",level:3},{value:"Build migrations",id:"build-migrations-cmake",level:3},{value:"Execute migrations",id:"execute-migrations-cmake",level:3},{value:"Migrations with qmake",id:"migrations-with-qmake",level:2},{value:"qmake project",id:"qmake-project",level:3},{value:"Auto-configure using .qmake.conf and .env",id:"auto-configure-using-qmakeconf-and-env",level:4},{value:"Migrations source files",id:"migrations-source-files",level:4},{value:"Seeders source files",id:"seeders-source-files",level:4},{value:"Build migrations",id:"build-migrations-qmake",level:3},{value:"Execute migrations",id:"execute-migrations-qmake",level:3},{value:"Finish",id:"finish",level:2}],h={toc:k},g="wrapper";function b(e){let{components:t,...m}=e;return(0,i.kt)(g,(0,a.Z)({},h,m,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"building-migrations"},"Building: Migrations"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#introduction"},"Introduction")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#install-dependencies"},"Install dependencies"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#using-vcpkg-json-manifest-mode"},"Using vcpkg.json")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#using-vcpkg-install-manually"},"Using vcpkg install")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#source-code"},"Source code"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#main-file"},"Main file")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#migrations"},"Migrations")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#seeders"},"Seeders")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#migrations-with-cmake"},"Migrations with CMake"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#cmake-project"},"CMake project")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#build-migrations-cmake"},"Build migrations")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#execute-migrations-cmake"},"Execute migrations")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#migrations-with-qmake"},"Migrations with qmake"),(0,i.kt)("ul",{parentName:"li"},(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#qmake-project"},"qmake project")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#build-migrations-qmake"},"Build migrations")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#execute-migrations-qmake"},"Execute migrations")))),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"#finish"},"Finish"))),(0,i.kt)("h2",{id:"introduction"},"Introduction"),(0,i.kt)("p",null,"We will try to create a working migrations console application called as ",(0,i.kt)("abbr",{title:"TinyORM migrations"},(0,i.kt)("inlineCode",{parentName:"p"},"tom"))," in the terminal with the ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," and in the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," with the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build systems."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," console application also expects the following ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure"),", let's create them."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.Fo)}\nmkdir tom/tom\ncd tom`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.q5)}\nmkdir -p tom/tom\ncd tom`))),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source tree contains the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," example application, you can inspire or look at the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/examples/tom"},"source code"),". Also, ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," unit tests use a ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," migrations internally to create the database structure, internally called as the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/tree/main/tests/testdata_tom"},(0,i.kt)("inlineCode",{parentName:"a"},"tom")," migrations for unit tests"),"."),(0,i.kt)("p",null,"All these three console applications the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," example, ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," migrations for unit tests, and the application described in this tutorial have practically identical source code (the main.cpp file)."),(0,i.kt)("admonition",{type:"note"},(0,i.kt)("p",{parentName:"admonition"},"The ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," is able to generate ",(0,i.kt)("a",{href:"https://en.wikipedia.org/wiki/Data_definition_language",title:"Data Definition Language"},"DDL")," queries for all the ",(0,i.kt)("a",{parentName:"p",href:"/database/getting-started#introduction"},"supported databases")," databases.")),(0,i.kt)("admonition",{type:"info"},(0,i.kt)("p",{parentName:"admonition"},"You can see the ",(0,i.kt)("a",{parentName:"p",href:"/features-summary#tom-console-application"},"Tom showcase image")," of how the resulting ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," console application will look like.")),(0,i.kt)("h2",{id:"install-dependencies"},"Install dependencies"),(0,i.kt)("p",null,"First, install the ",(0,i.kt)("inlineCode",{parentName:"p"},"vcpkg")," package manager as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#vcpkg"},"here"),"."),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries are required dependencies because ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," uses them in header files, you have to install them before you can use ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM"),". The ",(0,i.kt)("inlineCode",{parentName:"p"},"tabulate")," library is only needed in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," migrations it's used by the ",(0,i.kt)("inlineCode",{parentName:"p"},"migrate:status")," command."),(0,i.kt)("p",null,"There are two ways how to install the ",(0,i.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries using ",(0,i.kt)("inlineCode",{parentName:"p"},"vcpkg"),"."),(0,i.kt)("p",null,"Also, don't forget to build the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," library with the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," source code enabled (it's enabled by default) as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm"},"here"),"."),(0,i.kt)("h4",{id:"using-vcpkg-json-manifest-mode"},"Using vcpkg.json ",(0,i.kt)("small",null,"(manifest mode)")),(0,i.kt)("p",null,"Create a ",(0,i.kt)("inlineCode",{parentName:"p"},"vcpkg.json")," file with the following content. ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," example below uses this method."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd tom\nvim vcpkg.json\n")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-json",metastring:"title='vcpkg.json'",title:"'vcpkg.json'"},'{\n "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",\n "name": "tom",\n "version-semver": "0.1.0",\n "description": "Tom console application for TinyORM C++ library",\n "homepage": "https://github.com/silverqx/TinyORM",\n "documentation": "https://www.tinyorm.org/building/migrations",\n "maintainers": "Silver Zachara ",\n "supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",\n "dependencies": [\n "range-v3",\n "tabulate"\n ]\n}\n')),(0,i.kt)("admonition",{type:"note"},(0,i.kt)("p",{parentName:"admonition"},"Only ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," via the ",(0,i.kt)("inlineCode",{parentName:"p"},"toolchain file")," supports this method.")),(0,i.kt)("h4",{id:"using-vcpkg-install-manually"},"Using vcpkg install ",(0,i.kt)("small",null,"(manually)")),(0,i.kt)("p",null,"This method can be used with both ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../../vcpkg\n\nvcpkg search range-v3\nvcpkg search tabulate\nvcpkg install range-v3 tabulate\nvcpkg list\n")),(0,i.kt)("h2",{id:"source-code"},"Source code"),(0,i.kt)("p",null,"Let's start in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," project folder."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.Fo)}/tom/tom`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.q5)}/tom/tom`))),(0,i.kt)("h3",{id:"main-file"},"Main file"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"main.cpp")," source file."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"vim main.cpp\n")),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,i.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,i.kt)("kbd",null,"Shift")," + ",(0,i.kt)("kbd",null,"p"),".")),(0,i.kt)("p",null,"And paste the following code."),(0,i.kt)("a",{id:"string-constants-example"}),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='main.cpp'",title:"'main.cpp'"},'#include \n\n#include \n\n#include "migrations/2014_10_12_000000_create_posts_table.hpp"\n\n#include "seeders/databaseseeder.hpp"\n\nusing Orm::DatabaseManager;\nusing Orm::DB;\n\nusing TomApplication = Tom::Application;\n\nusing namespace Migrations; // NOLINT(google-build-using-namespace)\nusing namespace Seeders; // NOLINT(google-build-using-namespace)\n\n/*! Create the database manager instance and add a database connection. */\nstd::shared_ptr setupDatabaseManager();\n\n/*! C++ main function. */\nint main(int argc, char *argv[])\n{\n try {\n // Ownership of the shared_ptr()\n auto db = setupDatabaseManager();\n\n return TomApplication(argc, argv, std::move(db), "TOM_EXAMPLE_ENV")\n .migrations()\n .seeders()\n // Fire it up \ud83d\udd25\ud83d\ude80\u2728\n .run();\n\n } catch (const std::exception &e) {\n\n TomApplication::logException(e);\n }\n\n return EXIT_FAILURE;\n}\n\nstd::shared_ptr setupDatabaseManager()\n{\n using namespace Orm::Constants; // NOLINT(google-build-using-namespace)\n\n // Ownership of the shared_ptr()\n return DB::create({\n {driver_, QMYSQL},\n {host_, qEnvironmentVariable("DB_MYSQL_HOST", H127001)},\n {port_, qEnvironmentVariable("DB_MYSQL_PORT", P3306)},\n {database_, qEnvironmentVariable("DB_MYSQL_DATABASE", EMPTY)},\n {username_, qEnvironmentVariable("DB_MYSQL_USERNAME", EMPTY)},\n {password_, qEnvironmentVariable("DB_MYSQL_PASSWORD", EMPTY)},\n {charset_, qEnvironmentVariable("DB_MYSQL_CHARSET", UTF8MB4)},\n {collation_, qEnvironmentVariable("DB_MYSQL_COLLATION", UTF8MB40900aici)},\n {timezone_, TZ00},\n /* Specifies what time zone all QDateTime-s will have, the overridden default is\n the Qt::UTC, set to the Qt::LocalTime or QtTimeZoneType::DontConvert to use\n the system local time. */\n {qt_timezone, QVariant::fromValue(Qt::UTC)},\n {strict_, true},\n },\n QStringLiteral("tinyorm_tom_mysql")); // shell:connection\n}\n')),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"If you have defined more database connections then you can tag the lines with the database connection names with the ",(0,i.kt)("inlineCode",{parentName:"p"},"// shell:connection")," comment and this connection names will be provided to the bash, zsh, pwsh completions for the ",(0,i.kt)("inlineCode",{parentName:"p"},"--database=")," option \ud83d\ude0e, ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/examples/tom/main.cpp#L74"},"example"),".")),(0,i.kt)("h3",{id:"migrations"},"Migrations"),(0,i.kt)("p",null,"If you have already built the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application then you can generate a migrations using the ",(0,i.kt)("a",{parentName:"p",href:"/database/migrations#generating-migrations"},(0,i.kt)("inlineCode",{parentName:"a"},"make:migration"))," command \ud83d\ude0e."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"tom make:migration create_posts_table\n")),(0,i.kt)("p",null,"Below is the expected folders structure for the migrations. The ",(0,i.kt)("a",{parentName:"p",href:"#migrations-source-files"},(0,i.kt)("inlineCode",{parentName:"a"},"migrations.pri"))," file is used only by the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build system and is not needed with ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," builds."),(0,i.kt)("a",{id:"folders-structure"}),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-text"},"tom/\n\u2514\u2500\u2500 database/\n \u251c\u2500\u2500 migrations/\n \u251c\u2500\u2500 seeders/\n \u251c\u2500\u2500 migrations.pri\n \u2514\u2500\u2500 seeders.pri\n")),(0,i.kt)("p",null,"Let's create the first migration manually."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"mkdir database/migrations\n\nvim database/migrations/2014_10_12_000000_create_posts_table.hpp")),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"mkdir -p database/migrations\n\nvim database/migrations/2014_10_12_000000_create_posts_table.hpp"))),(0,i.kt)("p",null,"And paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='database/migrations/2014_10_12_000000_create_posts_table.hpp'",title:"'database/migrations/2014_10_12_000000_create_posts_table.hpp'"},'#pragma once\n\n#include \n\nnamespace Migrations\n{\n\n struct CreatePostsTable : Migration\n {\n /*! Filename of the migration file. */\n T_MIGRATION\n\n /*! Run the migrations. */\n void up() const override\n {\n Schema::create("posts", [](Blueprint &table)\n {\n table.id();\n\n table.string(NAME);\n table.timestamps();\n });\n }\n\n /*! Reverse the migrations. */\n void down() const override\n {\n Schema::dropIfExists("posts");\n }\n };\n\n} // namespace Migrations\n')),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"The ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source tree contains the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/tests/database/migrations/2014_10_12_000000_create_posts_table.hpp#L5"},(0,i.kt)("inlineCode",{parentName:"a"},"CreatePostsTable"))," example migration that also acts as the full-fledged example migration. It has defined and also nicely commented all possible features that migration classes can use or define.")),(0,i.kt)("admonition",{type:"info"},(0,i.kt)("p",{parentName:"admonition"},"If you want, you can also build the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application without the migrations, simply comment out the ",(0,i.kt)("inlineCode",{parentName:"p"},"migrations")," method and the corresponding ",(0,i.kt)("inlineCode",{parentName:"p"},'#include "migrations/xyz.hpp"')," files.")),(0,i.kt)("h3",{id:"seeders"},"Seeders"),(0,i.kt)("p",null,"If you have already built the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application then you can generate a seeder using the ",(0,i.kt)("a",{parentName:"p",href:"/database/seeding#writing-seeders"},(0,i.kt)("inlineCode",{parentName:"a"},"make:seeder"))," command \ud83d\ude0e."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"tom make:seeder PostSeeder\n")),(0,i.kt)("p",null,"The expected folders structure is described a few paragraphs ",(0,i.kt)("a",{parentName:"p",href:"#folders-structure"},"above"),". The ",(0,i.kt)("a",{parentName:"p",href:"#seeders-source-files"},(0,i.kt)("inlineCode",{parentName:"a"},"seeders.pri"))," file is used only by the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build system and is not needed with ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," builds."),(0,i.kt)("p",null,"Let's create the root seeder class manually."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"mkdir database/seeders\n\nvim database/seeders/databaseseeder.hpp")),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"mkdir -p database/seeders\n\nvim database/seeders/databaseseeder.hpp"))),(0,i.kt)("p",null,"And paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='database/seeders/databaseseeder.hpp'",title:"'database/seeders/databaseseeder.hpp'"},'#pragma once\n\n#include \n\nnamespace Seeders\n{\n\n /*! Main database seeder. */\n struct DatabaseSeeder : Seeder\n {\n /*! Run the database seeders. */\n void run() override\n {\n DB::table("posts")->insert({\n {{"name", "1. post"}},\n {{"name", "2. post"}},\n });\n }\n };\n\n} // namespace Seeders\n')),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"The ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source tree contains the ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/silverqx/TinyORM/blob/main/tests/database/seeders/databaseseeder.hpp#L8"},(0,i.kt)("inlineCode",{parentName:"a"},"DatabaseSeeder"))," root seeder example class that also acts as the full-fledged example seeder. It has defined and also nicely commented all possible features that seeder classes can use or define.")),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"You can create more seeder classes like this and use the ",(0,i.kt)("inlineCode",{parentName:"p"},"call<>()")," method to invoke them as is described in the ",(0,i.kt)("a",{parentName:"p",href:"/database/seeding#calling-additional-seeders"},"Calling Additional Seeders")," section.")),(0,i.kt)("h2",{id:"migrations-with-cmake"},"Migrations with CMake"),(0,i.kt)("p",null,"Create a folder for the ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," build."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"cd ..\nmkdir tom-builds-cmake/build-debug\n\ncd tom")),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"cd ..\nmkdir -p tom-builds-cmake/build-debug\n\ncd tom"))),(0,i.kt)("h3",{id:"cmake-project"},"CMake project"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file with the following content. I leave the comments in the ",(0,i.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file because it's not as simple as the ",(0,i.kt)("inlineCode",{parentName:"p"},"Hello world")," example; to make it clear what's going on."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-cmake",metastring:"title='CMakeLists.txt'",title:"'CMakeLists.txt'"},'cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\n# Specify the C++ standard\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\n# Initialize variables\n# ---\n\nset(Tom_ns tom)\nset(Tom_target tom)\n\nfile(REAL_PATH "../../TinyORM" TinyMainDir)\n\nset(TinyOrmSourceDir "${TinyMainDir}/TinyORM")\nset(TinyOrmBuildDir "${TinyMainDir}/TinyORM-builds-cmake/build-debug")\n\n# TinyORM CMake modules (needed to set the executable version and RC file on Windows)\nlist(APPEND CMAKE_MODULE_PATH "${TinyOrmSourceDir}/cmake/CommonModules")\n\n# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${TinyOrmBuildDir}")\n\n# Initialize Project Version\n# ---\n\ninclude(TinyHelpers)\ntiny_read_version(TINY_VERSION\n TINY_VERSION_MAJOR TINY_VERSION_MINOR TINY_VERSION_PATCH TINY_VERSION_TWEAK\n VERSION_HEADER "${TinyOrmSourceDir}/tom/include/tom/version.hpp"\n PREFIX TINYTOM\n HEADER_FOR "${Tom_ns}"\n)\n\n# Basic project\n# ---\n\nproject(${Tom_ns}\n DESCRIPTION "Tom console application for TinyORM C++ library"\n HOMEPAGE_URL "https://www.tinyorm.org"\n LANGUAGES CXX\n VERSION ${TINY_VERSION}\n)\n\n# Tom command-line application\n# ---\n\nadd_executable(${Tom_target}\n main.cpp\n)\nadd_executable(${Tom_ns}::${Tom_target} ALIAS ${Tom_target})\n\n# Tom command-line application specific configuration\n# ---\n\nset_target_properties(${Tom_target}\n PROPERTIES\n C_VISIBILITY_PRESET "hidden"\n CXX_VISIBILITY_PRESET "hidden"\n VISIBILITY_INLINES_HIDDEN YES\n VERSION ${PROJECT_VERSION}\n)\n\ntarget_include_directories(${Tom_target}\n PRIVATE "$"\n)\n\n# Tom command-line application defines\n# ---\n\ntarget_compile_definitions(${Tom_target}\n PRIVATE\n PROJECT_TOM\n)\n\n# Windows resource and manifest files\n# ---\n\n# Find icons, tom/version.hpp, and Windows manifest file for MinGW\nif(CMAKE_SYSTEM_NAME STREQUAL "Windows")\n tiny_set_rc_flags("-I \\"${TinyOrmSourceDir}/tom/resources\\"")\nendif()\n\ninclude(TinyResourceAndManifest)\ntiny_resource_and_manifest(${Tom_target}\n OUTPUT_DIR "${TINY_BUILD_GENDIR}/tmp/"\n RESOURCES_DIR "${TinyOrmSourceDir}/tom/resources"\n)\n\n# Resolve and link dependencies\n# ---\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.1 CONFIG REQUIRED)\n\n# Unconditional dependencies\ntarget_link_libraries(${Tom_target}\n PRIVATE\n Qt${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)\n')),(0,i.kt)("h3",{id:"build-migrations-cmake"},"Build migrations"),(0,i.kt)("p",null,"Now you are ready to configure ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," ",(0,i.kt)("inlineCode",{parentName:"p"},"CMake")," application. Don't forget to prepare the build environment with the ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#windows-prerequisites"},(0,i.kt)("inlineCode",{parentName:"a"},"qtenv6.ps1"))," command if you are building with the ",(0,i.kt)("inlineCode",{parentName:"p"},"msvc"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../tom-builds-cmake/build-debug\n")),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cmake.exe \`\n-S "${(0,p.go)(s.Fo)}/tom/tom" \`\n-B "${(0,p.go)(s.Fo)}/tom/tom-builds-cmake/build-debug" \`\n-G 'Ninja' \`\n-D CMAKE_BUILD_TYPE:STRING='Debug' \`\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(s.Fo)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \`\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(s.Fo)}/tmp/tom"`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cmake \\\n-S "${(0,p.go)(s.q5)}/tom/tom" \\\n-B "${(0,p.go)(s.q5)}/tom/tom-builds-cmake/build-debug" \\\n-G 'Ninja' \\\n-D CMAKE_BUILD_TYPE:STRING='Debug' \\\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(s.q5)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \\\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(s.q5)}/tmp/tom"`))),(0,i.kt)("p",null,"And build."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target all\n")),(0,i.kt)("h3",{id:"execute-migrations-cmake"},"Execute migrations"),(0,i.kt)("p",null,"Do not forget to add ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyOrm0d.dll")," on the path on Windows and on the ",(0,i.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application can find it during execution, as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#tinyorm-on-path-cmake"},"here"),"."),(0,i.kt)(l.Z,{groupId:s.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,p.go)(s.Fo,!1)}\\TinyORM\\TinyORM-builds-cmake\\build-debug;" + $env:Path`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,p.go)(s.q5)}/TinyORM/TinyORM-builds-cmake/build-debug\${PATH:+:}$PATH`))),(0,i.kt)("p",null,"Execute ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-powershell"},".\\tom.exe migrate:status\n"))),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"./tom migrate:status\n")))),(0,i.kt)("p",null,"The output will look something like this."),(0,i.kt)("img",{src:n(3086).Z,alt:"Tom migrations - migrate:status command output",width:"660"}),(0,i.kt)("p",null,"See also the ",(0,i.kt)("a",{parentName:"p",href:"#finish"},"final thoughts")," on how to verify the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," executable file properties."),(0,i.kt)("p",null,"Happy migrating \ud83c\udf89\ud83d\udc4c"),(0,i.kt)("h2",{id:"migrations-with-qmake"},"Migrations with qmake"),(0,i.kt)("p",null,"Create a folder for the ",(0,i.kt)("inlineCode",{parentName:"p"},"qmake")," build."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:s.IM,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.Fo)}/tom\n\nmkdir tom-builds-qmake`)),(0,i.kt)(r.Z,{value:s.q5,label:s.C,mdxType:"TabItem"},(0,i.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(s.q5)}/tom\n\nmkdir tom-builds-qmake`))),(0,i.kt)("p",null,"The ",(0,i.kt)("a",{parentName:"p",href:"#source-code"},(0,i.kt)("inlineCode",{parentName:"a"},"source code"))," is the same as for the ",(0,i.kt)("inlineCode",{parentName:"p"},"Migrations with CMake")," console application."),(0,i.kt)("h3",{id:"qmake-project"},"qmake project"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"tom.pro")," qmake file with the following content."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-bash"},"cd tom\nvim tom.pro\n")),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,i.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,i.kt)("kbd",null,"Shift")," + ",(0,i.kt)("kbd",null,"p"),".")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='tom.pro'",title:"'tom.pro'"},"QT -= gui\n\nTEMPLATE = app\nTARGET = tom\n\nCONFIG *= cmdline\n\nDEFINES *= PROJECT_TOM\n\nSOURCES += $$PWD/main.cpp\n\n# Database migrations\ninclude($$PWD/database/migrations.pri)\n# Database seeders\ninclude($$PWD/database/seeders.pri)\n\n# Auto-configure TinyORM library for the migrations purposes \ud83d\udd25\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/tom.pri)\n")),(0,i.kt)("admonition",{type:"caution"},(0,i.kt)("p",{parentName:"admonition"},"The exact ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," is crucial in this example because the paths to the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," source and build folders are relative.")),(0,i.kt)("admonition",{type:"caution"},(0,i.kt)("p",{parentName:"admonition"},"Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!")),(0,i.kt)("h4",{id:"auto-configure-using-qmakeconf-and-env"},(0,i.kt)("inlineCode",{parentName:"h4"},"Auto-configure")," using ",(0,i.kt)("inlineCode",{parentName:"h4"},".qmake.conf")," and ",(0,i.kt)("inlineCode",{parentName:"h4"},".env")),(0,i.kt)("p",null,"If you want to have properly configured ",(0,i.kt)("inlineCode",{parentName:"p"},"DEFINES")," (C preprocessor macros), have Qt headers marked as system headers, or eg. have properly set properties of an executable file such as version and description, then you need to specify a path to the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," qmake features (",(0,i.kt)("inlineCode",{parentName:"p"},".prf")," files) which handle this correctly; this path is provided by the ",(0,i.kt)("inlineCode",{parentName:"p"},"QMAKEFEATURES")," variable and can only be set in the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"Read the ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#consume-tinyorm-library-qmake"},"Consume TinyOrm library (qmake)")," section, as everything that is described in that section applies here as well.")),(0,i.kt)("p",null,"Create the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application root folder with the following content."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the PARENT folder of the TinyORM source folder\nTINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)\n# To find .env and .env.$$QMAKE_PLATFORM files\nTINY_DOTENV_ROOT = $$PWD\n# Path to the current build tree (used to guess the TinyORM build tree)\n#TINY_BUILD_TREE = $$shadowed($$PWD)\n\n# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants\nQMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)\n")),(0,i.kt)("p",null,"Then, create a ",(0,i.kt)("code",null,".env.(win32","|","unix","|","mingw)")," file in the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application root folder with the following content."),(0,i.kt)(l.Z,{groupId:s.IZ,mdxType:"Tabs"},(0,i.kt)(r.Z,{value:s.Fo,label:".env.win32",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in the tom.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)\n\n# Path to the vcpkg - range-v3 and tabulate\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-windows\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n"))),(0,i.kt)(r.Z,{value:s.q5,label:".env.unix",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in the tom.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_clang16_64bit_ccache-Debug/)\n\n# Path to the vcpkg - range-v3 and tabulate\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-linux\n\n# Use faster linker\nclang: CONFIG *= use_lld_linker\nelse: CONFIG *= use_gold_linker\n\n# Or use the mold linker\n#QMAKE_LFLAGS *= -fuse-ld=mold\n"))),(0,i.kt)(r.Z,{value:"mingw",label:".env.mingw",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in the tom.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSYS2_UCRT64_clang_64bit-Debug/)\n\n# Path to the vcpkg - range-v3 and tabulate\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-mingw-dynamic\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n\n# Use faster linker (for both GCC and Clang)\n# CONFIG *= use_lld_linker does not work on MinGW\nQMAKE_LFLAGS *= -fuse-ld=lld\n")))),(0,i.kt)("p",null,"Don't forget to update the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"TINY_VCPKG_ROOT")," folder paths to your needs if you are not using the recommended ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},(0,i.kt)("inlineCode",{parentName:"a"},"Folders structure")),"."),(0,i.kt)("p",null,"You can use the ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,i.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," if you don't like to specify it manually. Just comment out the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and uncomment the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINY_BUILD_TREE = $$shadowed($$PWD)")," in the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"You can entirely avoid the ",(0,i.kt)("inlineCode",{parentName:"p"},".env")," files, just move the ",(0,i.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," to the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," or remove it by help of ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,i.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," and set the ",(0,i.kt)("inlineCode",{parentName:"p"},"VCPKG_ROOT")," environment variable at system level as is described in ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#set-up-vcpkg-environment"},(0,i.kt)("inlineCode",{parentName:"a"},"Set up vcpkg environment")),".")),(0,i.kt)("admonition",{type:"info"},(0,i.kt)("p",{parentName:"admonition"},"Configuring by the ",(0,i.kt)("inlineCode",{parentName:"p"},".qmake.conf")," and ",(0,i.kt)("inlineCode",{parentName:"p"},".env")," files has one big advantage, which is that you don't have to modify the project files.")),(0,i.kt)("h4",{id:"migrations-source-files"},"Migrations source files"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"database/migrations.pri")," file and paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='database/migrations.pri'",title:"'database/migrations.pri'"},"INCLUDEPATH *= $$PWD\n\nHEADERS += \\\n $$PWD/migrations/2014_10_12_000000_create_posts_table.hpp \\\n")),(0,i.kt)("h4",{id:"seeders-source-files"},"Seeders source files"),(0,i.kt)("p",null,"Create ",(0,i.kt)("inlineCode",{parentName:"p"},"database/seeders.pri")," file and paste the following code."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='database/seeders.pri'",title:"'database/seeders.pri'"},"INCLUDEPATH *= $$PWD\n\nHEADERS += \\\n $$PWD/seeders/databaseseeder.hpp \\\n")),(0,i.kt)("h3",{id:"build-migrations-qmake"},"Build migrations"),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"I recommend creating a new ",(0,i.kt)("inlineCode",{parentName:"p"},"Session")," in the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#open-qtcreator-ide"},"here"),".")),(0,i.kt)("p",null,"Now you can open the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom.pro")," project in the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),"."),(0,i.kt)("p",null,"This will open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Configure Project")," tab, select some kit and update build folder paths to meet our ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," or like you want."),(0,i.kt)("img",{src:n(6191).Z,alt:"tom - QtCreator - Configure Project",width:"760"}),(0,i.kt)("admonition",{type:"tip"},(0,i.kt)("p",{parentName:"admonition"},"You can force the ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described ",(0,i.kt)("a",{parentName:"p",href:"/building/tinyorm#qtcreator-default-build-directory"},"here"),".")),(0,i.kt)("p",null,"You are ready to configure build options, hit ",(0,i.kt)("kbd",null,"Ctrl"),"+",(0,i.kt)("kbd",null,"5")," to open ",(0,i.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,i.kt)("inlineCode",{parentName:"p"},"Build")," in the left sidebar to open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Build Settings"),", it should look similar to the following picture."),(0,i.kt)("img",{src:n(5539).Z,className:"no-blurry",alt:"tom - QtCreator - Build Settings",width:"760"}),(0,i.kt)("p",null,"Disable ",(0,i.kt)("inlineCode",{parentName:"p"},"QML debugging and profiling")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"Qt Quick Compiler"),", they are not used."),(0,i.kt)("p",null,"In the left sidebar open ",(0,i.kt)("inlineCode",{parentName:"p"},"Dependencies")," and check ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," project and ",(0,i.kt)("inlineCode",{parentName:"p"},"Synchronize configuration"),", this setting ensures that the current project will be rebuilt correctly when the ",(0,i.kt)("inlineCode",{parentName:"p"},"TinyORM")," library source code changes."),(0,i.kt)("p",null,"Everything is ready to build, you can press ",(0,i.kt)("kbd",null,"Ctrl"),"+",(0,i.kt)("kbd",null,"b")," to build the project."),(0,i.kt)("h3",{id:"execute-migrations-qmake"},"Execute migrations"),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"QtCreator")," takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the ",(0,i.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux."),(0,i.kt)("p",null,"The only thing you might want to change is to run the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application in the new terminal window. To do so, hit ",(0,i.kt)("kbd",null,"Ctrl"),"+",(0,i.kt)("kbd",null,"5")," to open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,i.kt)("inlineCode",{parentName:"p"},"Run")," in the left sidebar to open the ",(0,i.kt)("inlineCode",{parentName:"p"},"Run Settings"),", then in the ",(0,i.kt)("inlineCode",{parentName:"p"},"Run")," section select the ",(0,i.kt)("inlineCode",{parentName:"p"},"Run in terminal")," checkbox."),(0,i.kt)("p",null,"You can also set the ",(0,i.kt)("inlineCode",{parentName:"p"},"Command line arguments")," in this ",(0,i.kt)("inlineCode",{parentName:"p"},"Run")," section, eg. the ",(0,i.kt)("inlineCode",{parentName:"p"},"migrate:status"),"."),(0,i.kt)("p",null,"To execute the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom")," application press ",(0,i.kt)("kbd",null,"Ctrl")," + ",(0,i.kt)("kbd",null,"r"),"."),(0,i.kt)("p",null,"The output will look ",(0,i.kt)("strong",{parentName:"p"},"very similar")," to this if you add more migrations."),(0,i.kt)("img",{src:n(3086).Z,alt:"Tom migrations - migrate:status command output",width:"660"}),(0,i.kt)("p",null,"Happy migrating \ud83c\udf89\ud83d\udc4c"),(0,i.kt)("h2",{id:"finish"},"Finish"),(0,i.kt)("p",null,"As the last thing, you can check that all the file properties were correctly set by the ",(0,i.kt)("a",{parentName:"p",href:"https://docs.microsoft.com/en-us/windows/win32/menurc/resource-compiler"},(0,i.kt)("inlineCode",{parentName:"a"},"rc"))," compiler."),(0,i.kt)("p",null,"Find the ",(0,i.kt)("inlineCode",{parentName:"p"},"tom.exe")," file and press ",(0,i.kt)("kbd",null,"Alt")," + ",(0,i.kt)("kbd",null,"Enter")," to open the file properties. To check the executable manifest you can use eg. the ",(0,i.kt)("a",{parentName:"p",href:"http://www.angusj.com/resourcehacker/"},"Resource Hacker"),"."),(0,i.kt)("img",{src:n(643).Z,alt:"tom.exe file properties detail",width:"440"}))}b.isMDXComponent=!0},5539:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-build_settings-e10927d1c4ed852620f9eb7564198940.png"},6191:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-configure_project-4721257090370204b0272d166512adef.png"},643:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/tom_file_properties-0df513c47ceadd5c09165e41c6b53086.png"},3086:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/tom_migrate_status-63c129a10bfe6bffe8d2d5ea280860e5.png"}}]); \ No newline at end of file diff --git a/assets/js/feaee7f3.d9eea7da.js b/assets/js/feaee7f3.700d4636.js similarity index 99% rename from assets/js/feaee7f3.d9eea7da.js rename to assets/js/feaee7f3.700d4636.js index a86e184a8..8647a0a6e 100644 --- a/assets/js/feaee7f3.d9eea7da.js +++ b/assets/js/feaee7f3.700d4636.js @@ -1 +1 @@ -"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[168],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>f});var a=n(7462),l=n(7294),o=n(6010),i=n(2466),r=n(6550),d=n(1980),p=n(7392),s=n(12);function u(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function c(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function k(e){let{queryString:t=!1,groupId:n}=e;const a=(0,r.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,d._X)(o),(0,l.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function h(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=c(e),[i,r]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[d,p]=k({queryString:n,groupId:a}),[u,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),g=(()=>{const e=d??u;return m({value:e,tabValues:o})?e:null})();(0,l.useLayoutEffect)((()=>{g&&r(g)}),[g]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);r(e),p(e),h(e)}),[p,h,o]),tabValues:o}}var g=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function N(e){let{className:t,block:n,selectedValue:r,selectValue:d,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),c=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==r&&(u(t),d(a))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:r===t?0:-1,"aria-selected":r===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":r===t})}),n??t)})))}function T(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function C(e){const t=h(e);return l.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},l.createElement(N,(0,a.Z)({},e,t)),l.createElement(T,(0,a.Z)({},e,t)))}function f(e){const t=(0,g.Z)();return l.createElement(C,(0,a.Z)({key:String(t)},e))}},2044:(e,t,n)=>{n.d(t,{$t:()=>u,Ae:()=>g,C:()=>k,DK:()=>b,Fo:()=>r,Fs:()=>l,IM:()=>h,IZ:()=>a,RS:()=>_,VE:()=>N,Wg:()=>C,_A:()=>p,al:()=>y,jk:()=>m,js:()=>d,of:()=>s,q5:()=>i,qb:()=>f,vk:()=>c,wU:()=>o,zg:()=>T});const a="shell",l="database",o="application",i="bash",r="pwsh",d="zsh",p="maria",s="mysql",u="postgres",c="sqlite",m="application",k="bash",h="pwsh",g="zsh",b="MariaDB",N="MySQL",T="PostgreSQL",C="SQLite",f="tinyorm.org",y="$HOME/Code/c/",_="$env:USERPROFILE\\Code\\c\\"},4355:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),l=n(9482);function o(){const e=(0,a.useContext)(l.Z);if(null!=e)return e;throw new Error("useRootFolderContext is used outside of Layout component.")}},6005:(e,t,n)=>{n.d(t,{AE:()=>r,EA:()=>i,em:()=>p,go:()=>d,mT:()=>s,we:()=>u});var a=n(4355),l=n(2389),o=n(2044);const i=function(e,t){return void 0===t&&(t=!0),c((0,a.Z)().rootFolder[e]??p(e),e,t)},r=()=>(0,a.Z)().rootFolder[o.wU]??p(o.wU),d=function(e,t){if(void 0===t&&(t=!0),null==e)throw new Error("The groupId in the applicationFolderPath() can not be empty.");const n=t||e!==o.Fo?"/":"\\";return c(i(e)+n+r(),e,t)};function p(e){if(null==e)throw new Error("The groupId in the folderDefaultValue() can not be empty.");if(!(0,l.Z)())return"";switch(e){case o.Fo:return o.RS;case o.q5:return o.al;case o.wU:return o.qb;default:throw new Error(`No default value for '${e}' groupId in the folderDefaultValue().`)}}function s(e){return e===o.wU}function u(e,t){if(null==t||""===t)return t;const n="$ENV{$1}$2";switch(e){case o.Fo:return k(t).replace(/\$env:(.+?)(\/.*)/,n);case o.q5:return t.replace(/\$(.+?)(\/.*)/,n);default:throw new Error(`Unsupported shell type '${e}' in the convertToCmakeEnvVariable().`)}}function c(e,t,n){if(void 0===n&&(n=!0),null==e||""===e)return e;if(t!==o.Fo)return m(e);const a=m(e);return n?k(a):function(e){return null==e||""===e?e:e.replaceAll(/\/+/g,"\\")}(a)}function m(e){return null==e||""===e?e:e.replace(/[/\\]+$/,"")}function k(e){return null==e||""===e?e:e.replaceAll(/\\+(?! )/g,"/")}},4588:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>m,contentTitle:()=>u,default:()=>b,frontMatter:()=>s,metadata:()=>c,toc:()=>k});var a=n(7462),l=(n(7294),n(3905)),o=n(7693),i=n(5162),r=n(4866),d=n(2044),p=n(6005);const s={sidebar_position:2,sidebar_label:"Hello world",description:"Hello world example created in the terminal and QtCreator IDE.",keywords:["c++ orm","building","hello world","tinyorm"]},u="Building: Hello world",c={unversionedId:"building/hello-world",id:"building/hello-world",title:"Building: Hello world",description:"Hello world example created in the terminal and QtCreator IDE.",source:"@site/docs/building/hello-world.mdx",sourceDirName:"building",slug:"/building/hello-world",permalink:"/building/hello-world",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/building/hello-world.mdx",tags:[],version:"current",sidebarPosition:2,frontMatter:{sidebar_position:2,sidebar_label:"Hello world",description:"Hello world example created in the terminal and QtCreator IDE.",keywords:["c++ orm","building","hello world","tinyorm"]},sidebar:"tinyormSidebar",previous:{title:"TinyORM",permalink:"/building/tinyorm"},next:{title:"Migrations",permalink:"/building/migrations"}},m={},k=[{value:"Introduction",id:"introduction",level:2},{value:"Prepare SQLite 3 database",id:"prepare-sqlite-3-database",level:2},{value:"Install dependencies",id:"install-dependencies",level:2},{value:"Using vcpkg.json (manifest mode)",id:"using-vcpkg-json-manifest-mode",level:4},{value:"Using vcpkg install (manually)",id:"using-vcpkg-install-manually",level:4},{value:"Source code",id:"source-code",level:2},{value:"Hello world with CMake",id:"hello-world-with-cmake",level:2},{value:"CMake project",id:"cmake-project",level:3},{value:"FetchContent",id:"fetchcontent",level:3},{value:"How FetchContent module works",id:"how-fetchcontent-module-works",level:4},{value:"Build Hello world",id:"build-hello-world-cmake",level:3},{value:"Execute Hello world",id:"execute-hello-world-cmake",level:3},{value:"Hello world with qmake",id:"hello-world-with-qmake",level:2},{value:"qmake project",id:"qmake-project",level:3},{value:"Auto-configure using .qmake.conf and .env",id:"auto-configure-using-qmake_conf-and-env",level:4},{value:"Build Hello world",id:"build-hello-world-qmake",level:3},{value:"Execute Hello world",id:"execute-hello-world-qmake",level:3}],h={toc:k},g="wrapper";function b(e){let{components:t,...s}=e;return(0,l.kt)(g,(0,a.Z)({},h,s,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("h1",{id:"building-hello-world"},"Building: Hello world"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#introduction"},"Introduction")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#prepare-sqlite-3-database"},"Prepare SQLite 3 database")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#install-dependencies"},"Install dependencies"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#using-vcpkg-json-manifest-mode"},"Using vcpkg.json")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#using-vcpkg-install-manually"},"Using vcpkg install")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#source-code"},"Source code")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#hello-world-with-cmake"},"Hello world with CMake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#cmake-project"},"CMake project")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#fetchcontent"},"FetchContent")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#build-hello-world-cmake"},"Build Hello world")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#execute-hello-world-cmake"},"Execute Hello world")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#hello-world-with-qmake"},"Hello world with qmake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#qmake-project"},"qmake project")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#build-hello-world-qmake"},"Build Hello world")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#execute-hello-world-qmake"},"Execute Hello world"))))),(0,l.kt)("h2",{id:"introduction"},"Introduction"),(0,l.kt)("p",null,"We will try to create the simplest working console application, in the terminal with the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," with the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build systems."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example also expects the following ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure"),", let's create them."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.Fo)}\nmkdir HelloWorld/HelloWorld\ncd HelloWorld`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.q5)}\nmkdir -p HelloWorld/HelloWorld\ncd HelloWorld`))),(0,l.kt)("h2",{id:"prepare-sqlite-3-database"},"Prepare SQLite 3 database"),(0,l.kt)("p",null,"The easiest way to demonstrate the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example will be with a ",(0,l.kt)("inlineCode",{parentName:"p"},"SQLite 3")," database."),(0,l.kt)("p",null,"Execute the following command in the terminal to create and insert two rows into the ",(0,l.kt)("inlineCode",{parentName:"p"},"SQLite 3")," database."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"sqlite3 HelloWorld.sqlite3 \"\ncreate table posts(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR NOT NULL);\ninsert into posts values(1, 'First Post');\ninsert into posts values(2, 'Second Post');\nselect * from posts;\"\n")),(0,l.kt)("h2",{id:"install-dependencies"},"Install dependencies"),(0,l.kt)("p",null,"First, install the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," package manager as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#vcpkg"},"here"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries are required dependencies because ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," uses them in header files, you have to install them before you can use ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM"),". The ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," library is only needed in the ",(0,l.kt)("inlineCode",{parentName:"p"},"tom")," migrations it's used by the ",(0,l.kt)("inlineCode",{parentName:"p"},"migrate:status")," command."),(0,l.kt)("p",null,"There are two ways how to install the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries using ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg"),"."),(0,l.kt)("h4",{id:"using-vcpkg-json-manifest-mode"},"Using vcpkg.json ",(0,l.kt)("small",null,"(manifest mode)")),(0,l.kt)("p",null,"Create a ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg.json")," file with the following content. ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," example below uses this method."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd HelloWorld\nvim vcpkg.json\n")),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-json",metastring:"title='vcpkg.json'",title:"'vcpkg.json'"},'{\n "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",\n "name": "tinyorm-helloworld",\n "version-semver": "0.1.0",\n "description": "Hello world console application for TinyORM C++ library",\n "homepage": "https://github.com/silverqx/TinyORM",\n "documentation": "https://www.tinyorm.org/building/hello-world",\n "maintainers": "Silver Zachara ",\n "supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",\n "dependencies": [\n "range-v3",\n "tabulate"\n ]\n}\n')),(0,l.kt)("admonition",{type:"note"},(0,l.kt)("p",{parentName:"admonition"},"Only ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," via the ",(0,l.kt)("inlineCode",{parentName:"p"},"toolchain file")," supports this method.")),(0,l.kt)("h4",{id:"using-vcpkg-install-manually"},"Using vcpkg install ",(0,l.kt)("small",null,"(manually)")),(0,l.kt)("p",null,"This method can be used with both ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake"),"."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../../vcpkg\n\nvcpkg search range-v3\nvcpkg search tabulate\nvcpkg install range-v3 tabulate\nvcpkg list\n")),(0,l.kt)("h2",{id:"source-code"},"Source code"),(0,l.kt)("p",null,"Let's start in the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," project folder."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.Fo)}/HelloWorld/HelloWorld`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.q5)}/HelloWorld/HelloWorld`))),(0,l.kt)("p",null,"Create ",(0,l.kt)("inlineCode",{parentName:"p"},"main.cpp")," source file."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"vim main.cpp\n")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,l.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,l.kt)("kbd",null,"Shift")," + ",(0,l.kt)("kbd",null,"p"),".")),(0,l.kt)("p",null,"And paste the following code."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='main.cpp'",title:"'main.cpp'"},'#include \n#include \n\n#ifdef _WIN32\n# include \n#endif\n\n#include \n\nusing Orm::DB;\n\nint main(int argc, char *argv[])\n{\n#ifdef _WIN32\n SetConsoleOutputCP(CP_UTF8);\n// SetConsoleOutputCP(1250);\n#endif\n\n /* Needed from Qt v6.5.3 to avoid:\n qt.core.qobject.connect: QObject::connect(QObject, Unknown): invalid nullptr parameter */\n QCoreApplication app(argc, argv);\n\n // Ownership of a shared_ptr()\n auto manager = DB::create({\n {"driver", "QSQLITE"},\n {"database", qEnvironmentVariable("TINYORM_HELLOWORLD_DB_SQLITE_DATABASE",\n "../../HelloWorld.sqlite3")},\n {"check_database_exists", true},\n });\n\n auto posts = DB::select("select * from posts");\n\n while(posts.next())\n qDebug() << posts.value("id").toULongLong()\n << posts.value("name").toString();\n}\n')),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"QSqlDatabase")," depends on ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," from ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt v6.5.3")," so you must create the ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," instance before you will call anything from the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. \ud83e\udee4 The change was made ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/qt/qtbase/commit/8d2bdc9cd5482eace12ba7e45304857bd24db0e6#diff-1d355c25c0b0eddec2be48253407780c4dc510d986739aec61e1ec892ccaf86e"},"here"),".")),(0,l.kt)("h2",{id:"hello-world-with-cmake"},"Hello world with CMake"),(0,l.kt)("p",null,"Create a folder for the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," build."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"cd ..\nmkdir HelloWorld-builds-cmake/build-debug\n\ncd HelloWorld")),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"cd ..\nmkdir -p HelloWorld-builds-cmake/build-debug\n\ncd HelloWorld"))),(0,l.kt)("h3",{id:"cmake-project"},"CMake project"),(0,l.kt)("p",null,"Create ",(0,l.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file with the following content."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.Fo,(0,p.go)(d.Fo))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt\${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.0 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt\${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.q5,(0,p.go)(d.q5))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt\${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.0 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt\${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)`))),(0,l.kt)("h3",{id:"fetchcontent"},"FetchContent"),(0,l.kt)("p",null,"If you don't have cloned and built the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library, or you want to quickly try TinyORM without wasting time with cloning and building the TinyORM library, then you can use CMake's ",(0,l.kt)("a",{parentName:"p",href:"https://cmake.org/cmake/help/latest/module/FetchContent.html"},(0,l.kt)("inlineCode",{parentName:"a"},"FetchContent"))," module that will do all of this for you."),(0,l.kt)("p",null,"Instead of providing a path by the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_PREFIX_PATH")," (or using the ",(0,l.kt)("inlineCode",{parentName:"p"},"User Package Registry"),") like in the example below:"),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.Fo,(0,p.go)(d.Fo))}/TinyORM/TinyORM-builds-cmake/build-debug")`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.q5,(0,p.go)(d.q5))}/TinyORM/TinyORM-builds-cmake/build-debug")`))),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("a",{parentName:"p",href:"https://cmake.org/cmake/help/latest/module/FetchContent.html"},(0,l.kt)("inlineCode",{parentName:"a"},"FetchContent"))," module like in the following example."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},"cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# FetchContent method\ninclude(FetchContent)\nFetchContent_Declare(TinyOrm\n GIT_REPOSITORY https://github.com/silverqx/TinyORM.git\n GIT_TAG origin/main\n OVERRIDE_FIND_PACKAGE\n)\n# Here you can configure TinyORM CMake options\nset(MYSQL_PING OFF)\nset(TOM_EXAMPLE ON)\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.0 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)")),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},'cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# FetchContent method\ninclude(FetchContent)\nFetchContent_Declare(TinyORM\n GIT_REPOSITORY https://github.com/silverqx/TinyORM.git\n GIT_TAG origin/main\n OVERRIDE_FIND_PACKAGE\n)\n# Here you can configure TinyORM CMake options\nset(MYSQL_PING OFF)\nset(TOM_EXAMPLE ON)\n\nTinyORM-builds-cmake/build-debug")\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.0 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)'))),(0,l.kt)("h4",{id:"how-fetchcontent-module-works"},"How FetchContent module works"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"FetchContent_Declare")," command is like calling the git clone inside the build folder and then adding a cloned folder in a similar way as the ",(0,l.kt)("inlineCode",{parentName:"p"},"add_subdirectory()")," command does."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"FetchContent_MakeAvailable()")," internally calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package()")," command or if you pass the ",(0,l.kt)("inlineCode",{parentName:"p"},"OVERRIDE_FIND_PACKAGE")," argument, then you don't have to call the the ",(0,l.kt)("inlineCode",{parentName:"p"},"FetchContent_MakeAvailable"),", but you must call the ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package( x.y.z CONFIG REQUIRED)")," command manually."),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"An advantage of the ",(0,l.kt)("inlineCode",{parentName:"p"},"OVERRIDE_FIND_PACKAGE")," argument is that you can call the ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package")," command much later, and you can insert additional configurations between.")),(0,l.kt)("h3",{id:"build-hello-world-cmake"},"Build Hello world"),(0,l.kt)("p",null,"Now you are ready to configure ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," application."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../HelloWorld-builds-cmake/build-debug\n")),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cmake.exe \`\n-S "${(0,p.go)(d.Fo)}/HelloWorld/HelloWorld" \`\n-B "${(0,p.go)(d.Fo)}/HelloWorld/HelloWorld-builds-cmake/build-debug" \`\n-G 'Ninja' \`\n-D CMAKE_BUILD_TYPE:STRING='Debug' \`\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(d.Fo)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \`\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(d.Fo)}/tmp/HelloWorld"`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cmake \\\n-S "${(0,p.go)(d.q5)}/HelloWorld/HelloWorld" \\\n-B "${(0,p.go)(d.q5)}/HelloWorld/HelloWorld-builds-cmake/build-debug" \\\n-G 'Ninja' \\\n-D CMAKE_BUILD_TYPE:STRING='Debug' \\\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(d.q5)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \\\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(d.q5)}/tmp/TinyORM"`))),(0,l.kt)("p",null,"And build."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target all\n")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"Enable the ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#cmake-strict_mode-option"},(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_STRICT_MODE"))," environment variable to produce better code and to follow good code practices.")),(0,l.kt)("h3",{id:"execute-hello-world-cmake"},"Execute Hello world"),(0,l.kt)("p",null,"Do not forget to add ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm0d.dll")," on the path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," application can find it during execution, as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#tinyorm-on-path-cmake"},"here"),"."),(0,l.kt)(r.Z,{groupId:d.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,p.go)(d.Fo,!1)}\\TinyORM\\TinyORM-builds-cmake\\build-debug;" + $env:Path`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,p.go)(d.q5)}/TinyORM/TinyORM-builds-cmake/build-debug\${PATH:+:}$PATH`))),(0,l.kt)("p",null,"Execute ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},".\\HelloWorld.exe\n"))),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"./HelloWorld\n")))),(0,l.kt)("p",null,"The output will look like this."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-less"},'Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts\n1 "First Post"\n2 "Second Post"\n')),(0,l.kt)("h2",{id:"hello-world-with-qmake"},"Hello world with qmake"),(0,l.kt)("p",null,"Create a folder for the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.Fo)}/HelloWorld\n\nmkdir HelloWorld-builds-qmake`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.q5)}/HelloWorld\n\nmkdir HelloWorld-builds-qmake`))),(0,l.kt)("p",null,"The ",(0,l.kt)("a",{parentName:"p",href:"#source-code"},(0,l.kt)("inlineCode",{parentName:"a"},"source code"))," is the same as for the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld CMake")," example."),(0,l.kt)("h3",{id:"qmake-project"},"qmake project"),(0,l.kt)("p",null,"Create ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld.pro")," qmake file with the following content."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd HelloWorld\nvim HelloWorld.pro\n")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,l.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,l.kt)("kbd",null,"Shift")," + ",(0,l.kt)("kbd",null,"p"),".")),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='HelloWorld.pro'",title:"'HelloWorld.pro'"},"QT -= gui\n\nTEMPLATE = app\n\nCONFIG *= cmdline\n\nDEFINES *= PROJECT_TINYORM_HELLOWORLD\n\nSOURCES += $$PWD/main.cpp\n\n# Auto-configure TinyORM library \ud83d\udd25\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n")),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"The exact ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," is crucial in this example because the paths to the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," source and build folders are relative.")),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!")),(0,l.kt)("h4",{id:"auto-configure-using-qmake_conf-and-env"},(0,l.kt)("inlineCode",{parentName:"h4"},"Auto-configure")," using ",(0,l.kt)("inlineCode",{parentName:"h4"},".qmake.conf")," and ",(0,l.kt)("inlineCode",{parentName:"h4"},".env")),(0,l.kt)("p",null,"If you want to have properly configured ",(0,l.kt)("inlineCode",{parentName:"p"},"DEFINES")," (C preprocessor macros) or have Qt headers marked as system headers, then you need to specify a path to the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," qmake features (",(0,l.kt)("inlineCode",{parentName:"p"},".prf")," files) which handle this correctly; this path is provided by the ",(0,l.kt)("inlineCode",{parentName:"p"},"QMAKEFEATURES")," variable and can only be set in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"Read the ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#consume-tinyorm-library-qmake"},"Consume TinyOrm library (qmake)")," section, as everything that is described in that section applies here as well.")),(0,l.kt)("p",null,"Create the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file in the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," project root folder with the following content."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the PARENT folder of the TinyORM source folder\nTINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)\n# To find .env and .env.$$QMAKE_PLATFORM files\nTINY_DOTENV_ROOT = $$PWD\n# Path to the current build tree (used to guess the TinyORM build tree)\n#TINY_BUILD_TREE = $$shadowed($$PWD)\n\n# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants\nQMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)\n")),(0,l.kt)("p",null,"Then, create a ",(0,l.kt)("code",null,".env.(win32","|","unix","|","mingw)")," file in the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," project root folder with the following content."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:".env.win32",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)\n\n# Path to the vcpkg - range-v3\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-windows\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n"))),(0,l.kt)(i.Z,{value:d.q5,label:".env.unix",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_clang16_64bit_ccache-Debug/)\n\n# Path to the vcpkg - range-v3\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-linux\n\n# Use faster linker\nclang: CONFIG *= use_lld_linker\nelse: CONFIG *= use_gold_linker\n\n# Or use the mold linker\n#QMAKE_LFLAGS *= -fuse-ld=mold\n"))),(0,l.kt)(i.Z,{value:"mingw",label:".env.mingw",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSYS2_UCRT64_clang_64bit-Debug/)\n\n# Path to the vcpkg - range-v3\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-mingw-dynamic\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n\n# Use faster linker (for both GCC and Clang)\n# CONFIG *= use_lld_linker does not work on MinGW\nQMAKE_LFLAGS *= -fuse-ld=lld\n")))),(0,l.kt)("p",null,"Don't forget to update the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_VCPKG_ROOT")," folder paths to your needs if you are not using the recommended ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},(0,l.kt)("inlineCode",{parentName:"a"},"Folders structure")),"."),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," if you don't like to specify it manually. Just comment out the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and uncomment the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_BUILD_TREE = $$shadowed($$PWD)")," in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can entirely avoid the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files, just move the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," to the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," or remove it by help of ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," and set the ",(0,l.kt)("inlineCode",{parentName:"p"},"VCPKG_ROOT")," environment variable at system level as is described in ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#set-up-vcpkg-environment"},(0,l.kt)("inlineCode",{parentName:"a"},"Set up vcpkg environment")),".")),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"Configuring by the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," and ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files has one big advantage, which is that you don't have to modify the project files.")),(0,l.kt)("h3",{id:"build-hello-world-qmake"},"Build Hello world"),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"I recommend creating a new ",(0,l.kt)("inlineCode",{parentName:"p"},"Session")," in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#open-qtcreator-ide"},"here"),".")),(0,l.kt)("p",null,"Now you can open the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld.pro")," project in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),"."),(0,l.kt)("p",null,"This will open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Configure Project")," tab, select some kit and update build folder paths to meet our ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," or like you want."),(0,l.kt)("img",{src:n(1465).Z,alt:"HelloWorld - QtCreator - Configure Project",width:"760"}),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can force the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#qtcreator-default-build-directory"},"here"),".")),(0,l.kt)("p",null,"You are ready to configure build options, hit ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"5")," to open ",(0,l.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,l.kt)("inlineCode",{parentName:"p"},"Build")," in the left sidebar to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Build Settings"),", it should look similar to the following picture."),(0,l.kt)("img",{src:n(6511).Z,className:"no-blurry",alt:"HelloWorld - QtCreator - Build Settings",width:"760"}),(0,l.kt)("p",null,"Disable ",(0,l.kt)("inlineCode",{parentName:"p"},"QML debugging and profiling")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt Quick Compiler"),", they are not used."),(0,l.kt)("p",null,"In the left sidebar open ",(0,l.kt)("inlineCode",{parentName:"p"},"Dependencies")," and check ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project and ",(0,l.kt)("inlineCode",{parentName:"p"},"Synchronize configuration"),", this setting ensures that the current project will be rebuilt correctly when the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library source code changes."),(0,l.kt)("p",null,"Everything is ready to build, you can press ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"b")," to build the project."),(0,l.kt)("h3",{id:"execute-hello-world-qmake"},"Execute Hello world"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux."),(0,l.kt)("p",null,"The only thing you might want to change is to run the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example in the new terminal window. To do so, hit ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"5")," to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,l.kt)("inlineCode",{parentName:"p"},"Run")," in the left sidebar to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Run Settings"),", then in the ",(0,l.kt)("inlineCode",{parentName:"p"},"Run")," section select the ",(0,l.kt)("inlineCode",{parentName:"p"},"Run in terminal")," checkbox."),(0,l.kt)("p",null,"To execute the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example press ",(0,l.kt)("kbd",null,"Ctrl")," + ",(0,l.kt)("kbd",null,"r"),"."),(0,l.kt)("p",null,"The output will look like this."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-less"},'Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts\n1 "First Post"\n2 "Second Post"\n')))}b.isMDXComponent=!0},6511:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-build_settings-ebdc6c0c056d11462096ff10cba682a1.png"},1465:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-configure_project-8caf87e6af4452f0c28bd15c85c392fc.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunktinyorm_org=self.webpackChunktinyorm_org||[]).push([[168],{5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),l=n(6010);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>f});var a=n(7462),l=n(7294),o=n(6010),i=n(2466),r=n(6550),d=n(1980),p=n(7392),s=n(12);function u(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function c(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??u(n);return function(e){const t=(0,p.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function k(e){let{queryString:t=!1,groupId:n}=e;const a=(0,r.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,d._X)(o),(0,l.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function h(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=c(e),[i,r]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[d,p]=k({queryString:n,groupId:a}),[u,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,s.Nk)(n);return[a,(0,l.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),g=(()=>{const e=d??u;return m({value:e,tabValues:o})?e:null})();(0,l.useLayoutEffect)((()=>{g&&r(g)}),[g]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);r(e),p(e),h(e)}),[p,h,o]),tabValues:o}}var g=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function N(e){let{className:t,block:n,selectedValue:r,selectValue:d,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.o5)(),c=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==r&&(u(t),d(a))},m=e=>{let t=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const n=s.indexOf(e.currentTarget)+1;t=s[n]??s[0];break}case"ArrowLeft":{const n=s.indexOf(e.currentTarget)-1;t=s[n]??s[s.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.Z)({role:"tab",tabIndex:r===t?0:-1,"aria-selected":r===t,key:t,ref:e=>s.push(e),onKeyDown:m,onClick:c},i,{className:(0,o.Z)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":r===t})}),n??t)})))}function T(e){let{lazy:t,children:n,selectedValue:a}=e;const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,l.cloneElement)(e,{className:"margin-top--md"}):null}return l.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,l.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function C(e){const t=h(e);return l.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},l.createElement(N,(0,a.Z)({},e,t)),l.createElement(T,(0,a.Z)({},e,t)))}function f(e){const t=(0,g.Z)();return l.createElement(C,(0,a.Z)({key:String(t)},e))}},2044:(e,t,n)=>{n.d(t,{$t:()=>u,Ae:()=>g,C:()=>k,DK:()=>b,Fo:()=>r,Fs:()=>l,IM:()=>h,IZ:()=>a,RS:()=>_,VE:()=>N,Wg:()=>C,_A:()=>p,al:()=>y,jk:()=>m,js:()=>d,of:()=>s,q5:()=>i,qb:()=>f,vk:()=>c,wU:()=>o,zg:()=>T});const a="shell",l="database",o="application",i="bash",r="pwsh",d="zsh",p="maria",s="mysql",u="postgres",c="sqlite",m="application",k="bash",h="pwsh",g="zsh",b="MariaDB",N="MySQL",T="PostgreSQL",C="SQLite",f="tinyorm.org",y="$HOME/Code/c/",_="$env:USERPROFILE\\Code\\c\\"},4355:(e,t,n)=>{n.d(t,{Z:()=>o});var a=n(7294),l=n(9482);function o(){const e=(0,a.useContext)(l.Z);if(null!=e)return e;throw new Error("useRootFolderContext is used outside of Layout component.")}},6005:(e,t,n)=>{n.d(t,{AE:()=>r,EA:()=>i,em:()=>p,go:()=>d,mT:()=>s,we:()=>u});var a=n(4355),l=n(2389),o=n(2044);const i=function(e,t){return void 0===t&&(t=!0),c((0,a.Z)().rootFolder[e]??p(e),e,t)},r=()=>(0,a.Z)().rootFolder[o.wU]??p(o.wU),d=function(e,t){if(void 0===t&&(t=!0),null==e)throw new Error("The groupId in the applicationFolderPath() can not be empty.");const n=t||e!==o.Fo?"/":"\\";return c(i(e)+n+r(),e,t)};function p(e){if(null==e)throw new Error("The groupId in the folderDefaultValue() can not be empty.");if(!(0,l.Z)())return"";switch(e){case o.Fo:return o.RS;case o.q5:return o.al;case o.wU:return o.qb;default:throw new Error(`No default value for '${e}' groupId in the folderDefaultValue().`)}}function s(e){return e===o.wU}function u(e,t){if(null==t||""===t)return t;const n="$ENV{$1}$2";switch(e){case o.Fo:return k(t).replace(/\$env:(.+?)(\/.*)/,n);case o.q5:return t.replace(/\$(.+?)(\/.*)/,n);default:throw new Error(`Unsupported shell type '${e}' in the convertToCmakeEnvVariable().`)}}function c(e,t,n){if(void 0===n&&(n=!0),null==e||""===e)return e;if(t!==o.Fo)return m(e);const a=m(e);return n?k(a):function(e){return null==e||""===e?e:e.replaceAll(/\/+/g,"\\")}(a)}function m(e){return null==e||""===e?e:e.replace(/[/\\]+$/,"")}function k(e){return null==e||""===e?e:e.replaceAll(/\\+(?! )/g,"/")}},4588:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>m,contentTitle:()=>u,default:()=>b,frontMatter:()=>s,metadata:()=>c,toc:()=>k});var a=n(7462),l=(n(7294),n(3905)),o=n(7693),i=n(5162),r=n(4866),d=n(2044),p=n(6005);const s={sidebar_position:2,sidebar_label:"Hello world",description:"Hello world example created in the terminal and QtCreator IDE.",keywords:["c++ orm","building","hello world","tinyorm"]},u="Building: Hello world",c={unversionedId:"building/hello-world",id:"building/hello-world",title:"Building: Hello world",description:"Hello world example created in the terminal and QtCreator IDE.",source:"@site/docs/building/hello-world.mdx",sourceDirName:"building",slug:"/building/hello-world",permalink:"/building/hello-world",draft:!1,editUrl:"https://github.com/silverqx/TinyORM-github.io/edit/main/docs/building/hello-world.mdx",tags:[],version:"current",sidebarPosition:2,frontMatter:{sidebar_position:2,sidebar_label:"Hello world",description:"Hello world example created in the terminal and QtCreator IDE.",keywords:["c++ orm","building","hello world","tinyorm"]},sidebar:"tinyormSidebar",previous:{title:"TinyORM",permalink:"/building/tinyorm"},next:{title:"Migrations",permalink:"/building/migrations"}},m={},k=[{value:"Introduction",id:"introduction",level:2},{value:"Prepare SQLite 3 database",id:"prepare-sqlite-3-database",level:2},{value:"Install dependencies",id:"install-dependencies",level:2},{value:"Using vcpkg.json (manifest mode)",id:"using-vcpkg-json-manifest-mode",level:4},{value:"Using vcpkg install (manually)",id:"using-vcpkg-install-manually",level:4},{value:"Source code",id:"source-code",level:2},{value:"Hello world with CMake",id:"hello-world-with-cmake",level:2},{value:"CMake project",id:"cmake-project",level:3},{value:"FetchContent",id:"fetchcontent",level:3},{value:"How FetchContent module works",id:"how-fetchcontent-module-works",level:4},{value:"Build Hello world",id:"build-hello-world-cmake",level:3},{value:"Execute Hello world",id:"execute-hello-world-cmake",level:3},{value:"Hello world with qmake",id:"hello-world-with-qmake",level:2},{value:"qmake project",id:"qmake-project",level:3},{value:"Auto-configure using .qmake.conf and .env",id:"auto-configure-using-qmake_conf-and-env",level:4},{value:"Build Hello world",id:"build-hello-world-qmake",level:3},{value:"Execute Hello world",id:"execute-hello-world-qmake",level:3}],h={toc:k},g="wrapper";function b(e){let{components:t,...s}=e;return(0,l.kt)(g,(0,a.Z)({},h,s,{components:t,mdxType:"MDXLayout"}),(0,l.kt)("h1",{id:"building-hello-world"},"Building: Hello world"),(0,l.kt)("ul",null,(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#introduction"},"Introduction")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#prepare-sqlite-3-database"},"Prepare SQLite 3 database")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#install-dependencies"},"Install dependencies"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#using-vcpkg-json-manifest-mode"},"Using vcpkg.json")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#using-vcpkg-install-manually"},"Using vcpkg install")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#source-code"},"Source code")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#hello-world-with-cmake"},"Hello world with CMake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#cmake-project"},"CMake project")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#fetchcontent"},"FetchContent")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#build-hello-world-cmake"},"Build Hello world")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#execute-hello-world-cmake"},"Execute Hello world")))),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#hello-world-with-qmake"},"Hello world with qmake"),(0,l.kt)("ul",{parentName:"li"},(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#qmake-project"},"qmake project")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#build-hello-world-qmake"},"Build Hello world")),(0,l.kt)("li",{parentName:"ul"},(0,l.kt)("a",{parentName:"li",href:"#execute-hello-world-qmake"},"Execute Hello world"))))),(0,l.kt)("h2",{id:"introduction"},"Introduction"),(0,l.kt)("p",null,"We will try to create the simplest working console application, in the terminal with the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," with the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build systems."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example also expects the following ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure"),", let's create them."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.Fo)}\nmkdir HelloWorld/HelloWorld\ncd HelloWorld`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.q5)}\nmkdir -p HelloWorld/HelloWorld\ncd HelloWorld`))),(0,l.kt)("h2",{id:"prepare-sqlite-3-database"},"Prepare SQLite 3 database"),(0,l.kt)("p",null,"The easiest way to demonstrate the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example will be with a ",(0,l.kt)("inlineCode",{parentName:"p"},"SQLite 3")," database."),(0,l.kt)("p",null,"Execute the following command in the terminal to create and insert two rows into the ",(0,l.kt)("inlineCode",{parentName:"p"},"SQLite 3")," database."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"sqlite3 HelloWorld.sqlite3 \"\ncreate table posts(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR NOT NULL);\ninsert into posts values(1, 'First Post');\ninsert into posts values(2, 'Second Post');\nselect * from posts;\"\n")),(0,l.kt)("h2",{id:"install-dependencies"},"Install dependencies"),(0,l.kt)("p",null,"First, install the ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg")," package manager as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#vcpkg"},"here"),"."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries are required dependencies because ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," uses them in header files, you have to install them before you can use ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM"),". The ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," library is only needed in the ",(0,l.kt)("inlineCode",{parentName:"p"},"tom")," migrations it's used by the ",(0,l.kt)("inlineCode",{parentName:"p"},"migrate:status")," command."),(0,l.kt)("p",null,"There are two ways how to install the ",(0,l.kt)("inlineCode",{parentName:"p"},"range-v3")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"tabulate")," libraries using ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg"),"."),(0,l.kt)("h4",{id:"using-vcpkg-json-manifest-mode"},"Using vcpkg.json ",(0,l.kt)("small",null,"(manifest mode)")),(0,l.kt)("p",null,"Create a ",(0,l.kt)("inlineCode",{parentName:"p"},"vcpkg.json")," file with the following content. ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," example below uses this method."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd HelloWorld\nvim vcpkg.json\n")),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-json",metastring:"title='vcpkg.json'",title:"'vcpkg.json'"},'{\n "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",\n "name": "tinyorm-helloworld",\n "version-semver": "0.1.0",\n "description": "Hello world console application for TinyORM C++ library",\n "homepage": "https://github.com/silverqx/TinyORM",\n "documentation": "https://www.tinyorm.org/building/hello-world",\n "maintainers": "Silver Zachara ",\n "supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",\n "dependencies": [\n "range-v3",\n "tabulate"\n ]\n}\n')),(0,l.kt)("admonition",{type:"note"},(0,l.kt)("p",{parentName:"admonition"},"Only ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," via the ",(0,l.kt)("inlineCode",{parentName:"p"},"toolchain file")," supports this method.")),(0,l.kt)("h4",{id:"using-vcpkg-install-manually"},"Using vcpkg install ",(0,l.kt)("small",null,"(manually)")),(0,l.kt)("p",null,"This method can be used with both ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake"),"."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../../vcpkg\n\nvcpkg search range-v3\nvcpkg search tabulate\nvcpkg install range-v3 tabulate\nvcpkg list\n")),(0,l.kt)("h2",{id:"source-code"},"Source code"),(0,l.kt)("p",null,"Let's start in the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," project folder."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.Fo)}/HelloWorld/HelloWorld`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.q5)}/HelloWorld/HelloWorld`))),(0,l.kt)("p",null,"Create ",(0,l.kt)("inlineCode",{parentName:"p"},"main.cpp")," source file."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"vim main.cpp\n")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,l.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,l.kt)("kbd",null,"Shift")," + ",(0,l.kt)("kbd",null,"p"),".")),(0,l.kt)("p",null,"And paste the following code."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-cpp",metastring:"title='main.cpp'",title:"'main.cpp'"},'#include \n#include \n\n#ifdef _WIN32\n# include \n#endif\n\n#include \n\nusing Orm::DB;\n\nint main(int argc, char *argv[])\n{\n#ifdef _WIN32\n SetConsoleOutputCP(CP_UTF8);\n// SetConsoleOutputCP(1250);\n#endif\n\n /* Needed from Qt v6.5.3 to avoid:\n qt.core.qobject.connect: QObject::connect(QObject, Unknown): invalid nullptr parameter */\n QCoreApplication app(argc, argv);\n\n // Ownership of a shared_ptr()\n auto manager = DB::create({\n {"driver", "QSQLITE"},\n {"database", qEnvironmentVariable("TINYORM_HELLOWORLD_DB_SQLITE_DATABASE",\n "../../HelloWorld.sqlite3")},\n {"check_database_exists", true},\n });\n\n auto posts = DB::select("select * from posts");\n\n while(posts.next())\n qDebug() << posts.value("id").toULongLong()\n << posts.value("name").toString();\n}\n')),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"The ",(0,l.kt)("inlineCode",{parentName:"p"},"QSqlDatabase")," depends on ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," from ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt v6.5.3")," so you must create the ",(0,l.kt)("inlineCode",{parentName:"p"},"QCoreApplication")," instance before you will call anything from the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library. \ud83e\udee4 The change was made ",(0,l.kt)("a",{parentName:"p",href:"https://github.com/qt/qtbase/commit/8d2bdc9cd5482eace12ba7e45304857bd24db0e6#diff-1d355c25c0b0eddec2be48253407780c4dc510d986739aec61e1ec892ccaf86e"},"here"),".")),(0,l.kt)("h2",{id:"hello-world-with-cmake"},"Hello world with CMake"),(0,l.kt)("p",null,"Create a folder for the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," build."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},"cd ..\nmkdir HelloWorld-builds-cmake/build-debug\n\ncd HelloWorld")),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},"cd ..\nmkdir -p HelloWorld-builds-cmake/build-debug\n\ncd HelloWorld"))),(0,l.kt)("h3",{id:"cmake-project"},"CMake project"),(0,l.kt)("p",null,"Create ",(0,l.kt)("inlineCode",{parentName:"p"},"CMakeLists.txt")," file with the following content."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.Fo,(0,p.go)(d.Fo))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt\${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.1 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt\${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.q5,(0,p.go)(d.q5))}/TinyORM/TinyORM-builds-cmake/build-debug")\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt\${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.1 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt\${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)`))),(0,l.kt)("h3",{id:"fetchcontent"},"FetchContent"),(0,l.kt)("p",null,"If you don't have cloned and built the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library, or you want to quickly try TinyORM without wasting time with cloning and building the TinyORM library, then you can use CMake's ",(0,l.kt)("a",{parentName:"p",href:"https://cmake.org/cmake/help/latest/module/FetchContent.html"},(0,l.kt)("inlineCode",{parentName:"a"},"FetchContent"))," module that will do all of this for you."),(0,l.kt)("p",null,"Instead of providing a path by the ",(0,l.kt)("inlineCode",{parentName:"p"},"CMAKE_PREFIX_PATH")," (or using the ",(0,l.kt)("inlineCode",{parentName:"p"},"User Package Registry"),") like in the example below:"),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.Fo,(0,p.go)(d.Fo))}/TinyORM/TinyORM-builds-cmake/build-debug")`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},`# build tree\nlist(APPEND CMAKE_PREFIX_PATH "${(0,p.we)(d.q5,(0,p.go)(d.q5))}/TinyORM/TinyORM-builds-cmake/build-debug")`))),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("a",{parentName:"p",href:"https://cmake.org/cmake/help/latest/module/FetchContent.html"},(0,l.kt)("inlineCode",{parentName:"a"},"FetchContent"))," module like in the following example."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},"cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# FetchContent method\ninclude(FetchContent)\nFetchContent_Declare(TinyOrm\n GIT_REPOSITORY https://github.com/silverqx/TinyORM.git\n GIT_TAG origin/main\n OVERRIDE_FIND_PACKAGE\n)\n# Here you can configure TinyORM CMake options\nset(MYSQL_PING OFF)\nset(TOM_EXAMPLE ON)\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.1 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)")),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-cmake",mdxType:"CodeBlock"},'cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)\n\nproject(HelloWorld LANGUAGES CXX)\n\n# FetchContent method\ninclude(FetchContent)\nFetchContent_Declare(TinyORM\n GIT_REPOSITORY https://github.com/silverqx/TinyORM.git\n GIT_TAG origin/main\n OVERRIDE_FIND_PACKAGE\n)\n# Here you can configure TinyORM CMake options\nset(MYSQL_PING OFF)\nset(TOM_EXAMPLE ON)\n\nTinyORM-builds-cmake/build-debug")\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nadd_executable(HelloWorld\n main.cpp\n)\n\nfind_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)\nfind_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)\nfind_package(TinyOrm 0.37.1 CONFIG REQUIRED)\n\ntarget_link_libraries(HelloWorld\n PRIVATE\n Qt${QT_VERSION_MAJOR}::Core\n TinyOrm::TinyOrm\n)'))),(0,l.kt)("h4",{id:"how-fetchcontent-module-works"},"How FetchContent module works"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"FetchContent_Declare")," command is like calling the git clone inside the build folder and then adding a cloned folder in a similar way as the ",(0,l.kt)("inlineCode",{parentName:"p"},"add_subdirectory()")," command does."),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"FetchContent_MakeAvailable()")," internally calls the ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package()")," command or if you pass the ",(0,l.kt)("inlineCode",{parentName:"p"},"OVERRIDE_FIND_PACKAGE")," argument, then you don't have to call the the ",(0,l.kt)("inlineCode",{parentName:"p"},"FetchContent_MakeAvailable"),", but you must call the ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package( x.y.z CONFIG REQUIRED)")," command manually."),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"An advantage of the ",(0,l.kt)("inlineCode",{parentName:"p"},"OVERRIDE_FIND_PACKAGE")," argument is that you can call the ",(0,l.kt)("inlineCode",{parentName:"p"},"find_package")," command much later, and you can insert additional configurations between.")),(0,l.kt)("h3",{id:"build-hello-world-cmake"},"Build Hello world"),(0,l.kt)("p",null,"Now you are ready to configure ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," ",(0,l.kt)("inlineCode",{parentName:"p"},"CMake")," application."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd ../HelloWorld-builds-cmake/build-debug\n")),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cmake.exe \`\n-S "${(0,p.go)(d.Fo)}/HelloWorld/HelloWorld" \`\n-B "${(0,p.go)(d.Fo)}/HelloWorld/HelloWorld-builds-cmake/build-debug" \`\n-G 'Ninja' \`\n-D CMAKE_BUILD_TYPE:STRING='Debug' \`\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(d.Fo)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \`\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(d.Fo)}/tmp/HelloWorld"`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cmake \\\n-S "${(0,p.go)(d.q5)}/HelloWorld/HelloWorld" \\\n-B "${(0,p.go)(d.q5)}/HelloWorld/HelloWorld-builds-cmake/build-debug" \\\n-G 'Ninja' \\\n-D CMAKE_BUILD_TYPE:STRING='Debug' \\\n-D CMAKE_TOOLCHAIN_FILE:FILEPATH="${(0,p.EA)(d.q5)}/vcpkg/scripts/buildsystems/vcpkg.cmake" \\\n-D CMAKE_INSTALL_PREFIX:PATH="${(0,p.EA)(d.q5)}/tmp/TinyORM"`))),(0,l.kt)("p",null,"And build."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cmake --build . --target all\n")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"Enable the ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#cmake-strict_mode-option"},(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_STRICT_MODE"))," environment variable to produce better code and to follow good code practices.")),(0,l.kt)("h3",{id:"execute-hello-world-cmake"},"Execute Hello world"),(0,l.kt)("p",null,"Do not forget to add ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyOrm0d.dll")," on the path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux, so ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," application can find it during execution, as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#tinyorm-on-path-cmake"},"here"),"."),(0,l.kt)(r.Z,{groupId:d.IZ,name:"tinyorm-on-path",mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`$env:Path = "${(0,p.go)(d.Fo,!1)}\\TinyORM\\TinyORM-builds-cmake\\build-debug;" + $env:Path`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`export LD_LIBRARY_PATH=${(0,p.go)(d.q5)}/TinyORM/TinyORM-builds-cmake/build-debug\${PATH:+:}$PATH`))),(0,l.kt)("p",null,"Execute ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-powershell"},".\\HelloWorld.exe\n"))),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"./HelloWorld\n")))),(0,l.kt)("p",null,"The output will look like this."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-less"},'Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts\n1 "First Post"\n2 "Second Post"\n')),(0,l.kt)("h2",{id:"hello-world-with-qmake"},"Hello world with qmake"),(0,l.kt)("p",null,"Create a folder for the ",(0,l.kt)("inlineCode",{parentName:"p"},"qmake")," build."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:d.IM,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-powershell",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.Fo)}/HelloWorld\n\nmkdir HelloWorld-builds-qmake`)),(0,l.kt)(i.Z,{value:d.q5,label:d.C,mdxType:"TabItem"},(0,l.kt)(o.Z,{className:"language-bash",mdxType:"CodeBlock"},`cd ${(0,p.go)(d.q5)}/HelloWorld\n\nmkdir HelloWorld-builds-qmake`))),(0,l.kt)("p",null,"The ",(0,l.kt)("a",{parentName:"p",href:"#source-code"},(0,l.kt)("inlineCode",{parentName:"a"},"source code"))," is the same as for the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld CMake")," example."),(0,l.kt)("h3",{id:"qmake-project"},"qmake project"),(0,l.kt)("p",null,"Create ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld.pro")," qmake file with the following content."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-bash"},"cd HelloWorld\nvim HelloWorld.pro\n")),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"To paste a source code correctly in ",(0,l.kt)("inlineCode",{parentName:"p"},"vim"),", press ",(0,l.kt)("kbd",null,"Shift")," + ",(0,l.kt)("kbd",null,"p"),".")),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='HelloWorld.pro'",title:"'HelloWorld.pro'"},"QT -= gui\n\nTEMPLATE = app\n\nCONFIG *= cmdline\n\nDEFINES *= PROJECT_TINYORM_HELLOWORLD\n\nSOURCES += $$PWD/main.cpp\n\n# Auto-configure TinyORM library \ud83d\udd25\ninclude($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)\n")),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"The exact ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," is crucial in this example because the paths to the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," source and build folders are relative.")),(0,l.kt)("admonition",{type:"caution"},(0,l.kt)("p",{parentName:"admonition"},"Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!")),(0,l.kt)("h4",{id:"auto-configure-using-qmake_conf-and-env"},(0,l.kt)("inlineCode",{parentName:"h4"},"Auto-configure")," using ",(0,l.kt)("inlineCode",{parentName:"h4"},".qmake.conf")," and ",(0,l.kt)("inlineCode",{parentName:"h4"},".env")),(0,l.kt)("p",null,"If you want to have properly configured ",(0,l.kt)("inlineCode",{parentName:"p"},"DEFINES")," (C preprocessor macros) or have Qt headers marked as system headers, then you need to specify a path to the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," qmake features (",(0,l.kt)("inlineCode",{parentName:"p"},".prf")," files) which handle this correctly; this path is provided by the ",(0,l.kt)("inlineCode",{parentName:"p"},"QMAKEFEATURES")," variable and can only be set in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"Read the ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#consume-tinyorm-library-qmake"},"Consume TinyOrm library (qmake)")," section, as everything that is described in that section applies here as well.")),(0,l.kt)("p",null,"Create the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file in the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," project root folder with the following content."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake",metastring:"title='.qmake.conf'",title:"'.qmake.conf'"},"# Path to the PARENT folder of the TinyORM source folder\nTINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)\n# To find .env and .env.$$QMAKE_PLATFORM files\nTINY_DOTENV_ROOT = $$PWD\n# Path to the current build tree (used to guess the TinyORM build tree)\n#TINY_BUILD_TREE = $$shadowed($$PWD)\n\n# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants\nQMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)\n")),(0,l.kt)("p",null,"Then, create a ",(0,l.kt)("code",null,".env.(win32","|","unix","|","mingw)")," file in the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," project root folder with the following content."),(0,l.kt)(r.Z,{groupId:d.IZ,mdxType:"Tabs"},(0,l.kt)(i.Z,{value:d.Fo,label:".env.win32",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)\n\n# Path to the vcpkg - range-v3\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-windows\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n"))),(0,l.kt)(i.Z,{value:d.q5,label:".env.unix",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_clang16_64bit_ccache-Debug/)\n\n# Path to the vcpkg - range-v3\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-linux\n\n# Use faster linker\nclang: CONFIG *= use_lld_linker\nelse: CONFIG *= use_gold_linker\n\n# Or use the mold linker\n#QMAKE_LFLAGS *= -fuse-ld=mold\n"))),(0,l.kt)(i.Z,{value:"mingw",label:".env.mingw",mdxType:"TabItem"},(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-qmake"},"# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro\n# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!\n\n# Path to the TinyORM build folder\nTINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSYS2_UCRT64_clang_64bit-Debug/)\n\n# Path to the vcpkg - range-v3\n# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty\nTINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)\nTINY_VCPKG_TRIPLET = x64-mingw-dynamic\n\n# Enable ccache wrapper\n#CONFIG *= tiny_ccache_win32\n\n# Use faster linker (for both GCC and Clang)\n# CONFIG *= use_lld_linker does not work on MinGW\nQMAKE_LFLAGS *= -fuse-ld=lld\n")))),(0,l.kt)("p",null,"Don't forget to update the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_VCPKG_ROOT")," folder paths to your needs if you are not using the recommended ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},(0,l.kt)("inlineCode",{parentName:"a"},"Folders structure")),"."),(0,l.kt)("p",null,"You can use the ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," if you don't like to specify it manually. Just comment out the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," and uncomment the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINY_BUILD_TREE = $$shadowed($$PWD)")," in the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," file."),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can entirely avoid the ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files, just move the ",(0,l.kt)("inlineCode",{parentName:"p"},"TINYORM_BUILD_TREE")," to the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," or remove it by help of ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#partial-guessing-of-the-tinyorm_build_tree"},"Partial guessing of the ",(0,l.kt)("inlineCode",{parentName:"a"},"TINYORM_BUILD_TREE"))," and set the ",(0,l.kt)("inlineCode",{parentName:"p"},"VCPKG_ROOT")," environment variable at system level as is described in ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#set-up-vcpkg-environment"},(0,l.kt)("inlineCode",{parentName:"a"},"Set up vcpkg environment")),".")),(0,l.kt)("admonition",{type:"info"},(0,l.kt)("p",{parentName:"admonition"},"Configuring by the ",(0,l.kt)("inlineCode",{parentName:"p"},".qmake.conf")," and ",(0,l.kt)("inlineCode",{parentName:"p"},".env")," files has one big advantage, which is that you don't have to modify the project files.")),(0,l.kt)("h3",{id:"build-hello-world-qmake"},"Build Hello world"),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"I recommend creating a new ",(0,l.kt)("inlineCode",{parentName:"p"},"Session")," in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE")," as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#open-qtcreator-ide"},"here"),".")),(0,l.kt)("p",null,"Now you can open the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld.pro")," project in the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator IDE"),"."),(0,l.kt)("p",null,"This will open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Configure Project")," tab, select some kit and update build folder paths to meet our ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#folders-structure"},"folders structure")," or like you want."),(0,l.kt)("img",{src:n(1465).Z,alt:"HelloWorld - QtCreator - Configure Project",width:"760"}),(0,l.kt)("admonition",{type:"tip"},(0,l.kt)("p",{parentName:"admonition"},"You can force the ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," to generate a build folders structure as is described ",(0,l.kt)("a",{parentName:"p",href:"/building/tinyorm#qtcreator-default-build-directory"},"here"),".")),(0,l.kt)("p",null,"You are ready to configure build options, hit ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"5")," to open ",(0,l.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,l.kt)("inlineCode",{parentName:"p"},"Build")," in the left sidebar to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Build Settings"),", it should look similar to the following picture."),(0,l.kt)("img",{src:n(6511).Z,className:"no-blurry",alt:"HelloWorld - QtCreator - Build Settings",width:"760"}),(0,l.kt)("p",null,"Disable ",(0,l.kt)("inlineCode",{parentName:"p"},"QML debugging and profiling")," and ",(0,l.kt)("inlineCode",{parentName:"p"},"Qt Quick Compiler"),", they are not used."),(0,l.kt)("p",null,"In the left sidebar open ",(0,l.kt)("inlineCode",{parentName:"p"},"Dependencies")," and check ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," project and ",(0,l.kt)("inlineCode",{parentName:"p"},"Synchronize configuration"),", this setting ensures that the current project will be rebuilt correctly when the ",(0,l.kt)("inlineCode",{parentName:"p"},"TinyORM")," library source code changes."),(0,l.kt)("p",null,"Everything is ready to build, you can press ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"b")," to build the project."),(0,l.kt)("h3",{id:"execute-hello-world-qmake"},"Execute Hello world"),(0,l.kt)("p",null,"The ",(0,l.kt)("inlineCode",{parentName:"p"},"QtCreator")," takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the ",(0,l.kt)("inlineCode",{parentName:"p"},"LD_LIBRARY_PATH")," on Linux."),(0,l.kt)("p",null,"The only thing you might want to change is to run the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example in the new terminal window. To do so, hit ",(0,l.kt)("kbd",null,"Ctrl"),"+",(0,l.kt)("kbd",null,"5")," to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Project Settings")," tab and select ",(0,l.kt)("inlineCode",{parentName:"p"},"Run")," in the left sidebar to open the ",(0,l.kt)("inlineCode",{parentName:"p"},"Run Settings"),", then in the ",(0,l.kt)("inlineCode",{parentName:"p"},"Run")," section select the ",(0,l.kt)("inlineCode",{parentName:"p"},"Run in terminal")," checkbox."),(0,l.kt)("p",null,"To execute the ",(0,l.kt)("inlineCode",{parentName:"p"},"HelloWorld")," example press ",(0,l.kt)("kbd",null,"Ctrl")," + ",(0,l.kt)("kbd",null,"r"),"."),(0,l.kt)("p",null,"The output will look like this."),(0,l.kt)("pre",null,(0,l.kt)("code",{parentName:"pre",className:"language-less"},'Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts\n1 "First Post"\n2 "Second Post"\n')))}b.isMDXComponent=!0},6511:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-build_settings-ebdc6c0c056d11462096ff10cba682a1.png"},1465:(e,t,n)=>{n.d(t,{Z:()=>a});const a=n.p+"assets/images/qmake-configure_project-8caf87e6af4452f0c28bd15c85c392fc.png"}}]); \ No newline at end of file diff --git a/assets/js/runtime~main.767f632f.js b/assets/js/runtime~main.dd99a9a8.js similarity index 79% rename from assets/js/runtime~main.767f632f.js rename to assets/js/runtime~main.dd99a9a8.js index aa23e9d4e..638fd34c5 100644 --- a/assets/js/runtime~main.767f632f.js +++ b/assets/js/runtime~main.dd99a9a8.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,r,a,o,f={},n={};function c(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return f[e].call(r.exports,r,r.exports,c),r.exports}c.m=f,e=[],c.O=(t,r,a,o)=>{if(!r){var f=1/0;for(i=0;i=o)&&Object.keys(c.O).every((e=>c.O[e](r[d])))?r.splice(d--,1):(n=!1,o0&&e[i-1][2]>o;i--)e[i]=e[i-1];e[i]=[r,a,o]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,a){if(1&a&&(e=this(e)),8&a)return e;if("object"==typeof e&&e){if(4&a&&e.__esModule)return e;if(16&a&&"function"==typeof e.then)return e}var o=Object.create(null);c.r(o);var f={};t=t||[null,r({}),r([]),r(r)];for(var n=2&a&&e;"object"==typeof n&&!~t.indexOf(n);n=r(n))Object.getOwnPropertyNames(n).forEach((t=>f[t]=()=>e[t]));return f.default=()=>e,c.d(o,f),o},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce(((t,r)=>(c.f[r](e,t),t)),[])),c.u=e=>"assets/js/"+({8:"e3ac21cb",53:"935f2afb",57:"62a1276f",67:"59b1a96c",108:"3dd307b5",113:"cdf0eeb2",116:"5b254f70",168:"feaee7f3",225:"8a8faf8d",291:"21dc2778",454:"a4d3e054",514:"1be78505",535:"1222ea4e",594:"cbe663fe",683:"8156e19a",684:"cb1e72f9",784:"ba3d4959",799:"7333c691",832:"fb313d4e",865:"e19c288b",918:"17896441",920:"1a4e3797",966:"d459b1c4",969:"0ab078a9"}[e]||e)+"."+{8:"9751aa02",53:"c45c3ca0",57:"732e44fe",67:"6afbbfdf",108:"7b464df0",113:"29f89fc3",116:"287f094d",168:"d9eea7da",176:"1f8f2d9b",225:"3f5122a9",291:"c3cad2a2",426:"97069429",454:"2c177800",514:"fb48f26a",535:"93c74363",594:"8fc7d46f",683:"5e01ccd6",684:"c0a429c9",784:"86bd32f7",799:"d4a3b177",832:"246c2a2a",865:"8ce43523",894:"1afcfcdd",918:"35ffcf9d",920:"ca05490f",945:"62d4a71f",966:"7a1fface",969:"34078f5e",972:"b9e804c8"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a={},o="tinyorm.org:",c.l=(e,t,r,f)=>{if(a[e])a[e].push(t);else{var n,d;if(void 0!==r)for(var b=document.getElementsByTagName("script"),i=0;i{n.onerror=n.onload=null,clearTimeout(s);var o=a[e];if(delete a[e],n.parentNode&&n.parentNode.removeChild(n),o&&o.forEach((e=>e(r))),t)return t(r)},s=setTimeout(l.bind(null,void 0,{type:"timeout",target:n}),12e4);n.onerror=l.bind(null,n.onerror),n.onload=l.bind(null,n.onload),d&&document.head.appendChild(n)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.p="/",c.gca=function(e){return e={17896441:"918",e3ac21cb:"8","935f2afb":"53","62a1276f":"57","59b1a96c":"67","3dd307b5":"108",cdf0eeb2:"113","5b254f70":"116",feaee7f3:"168","8a8faf8d":"225","21dc2778":"291",a4d3e054:"454","1be78505":"514","1222ea4e":"535",cbe663fe:"594","8156e19a":"683",cb1e72f9:"684",ba3d4959:"784","7333c691":"799",fb313d4e:"832",e19c288b:"865","1a4e3797":"920",d459b1c4:"966","0ab078a9":"969"}[e]||e,c.p+c.u(e)},(()=>{var e={303:0,532:0};c.f.j=(t,r)=>{var a=c.o(e,t)?e[t]:void 0;if(0!==a)if(a)r.push(a[2]);else if(/^(303|532)$/.test(t))e[t]=0;else{var o=new Promise(((r,o)=>a=e[t]=[r,o]));r.push(a[2]=o);var f=c.p+c.u(t),n=new Error;c.l(f,(r=>{if(c.o(e,t)&&(0!==(a=e[t])&&(e[t]=void 0),a)){var o=r&&("load"===r.type?"missing":r.type),f=r&&r.target&&r.target.src;n.message="Loading chunk "+t+" failed.\n("+o+": "+f+")",n.name="ChunkLoadError",n.type=o,n.request=f,a[1](n)}}),"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var a,o,f=r[0],n=r[1],d=r[2],b=0;if(f.some((t=>0!==e[t]))){for(a in n)c.o(n,a)&&(c.m[a]=n[a]);if(d)var i=d(c)}for(t&&t(r);b{"use strict";var e,t,r,a,o,f={},n={};function c(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return f[e].call(r.exports,r,r.exports,c),r.exports}c.m=f,e=[],c.O=(t,r,a,o)=>{if(!r){var f=1/0;for(b=0;b=o)&&Object.keys(c.O).every((e=>c.O[e](r[d])))?r.splice(d--,1):(n=!1,o0&&e[b-1][2]>o;b--)e[b]=e[b-1];e[b]=[r,a,o]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,a){if(1&a&&(e=this(e)),8&a)return e;if("object"==typeof e&&e){if(4&a&&e.__esModule)return e;if(16&a&&"function"==typeof e.then)return e}var o=Object.create(null);c.r(o);var f={};t=t||[null,r({}),r([]),r(r)];for(var n=2&a&&e;"object"==typeof n&&!~t.indexOf(n);n=r(n))Object.getOwnPropertyNames(n).forEach((t=>f[t]=()=>e[t]));return f.default=()=>e,c.d(o,f),o},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce(((t,r)=>(c.f[r](e,t),t)),[])),c.u=e=>"assets/js/"+({8:"e3ac21cb",53:"935f2afb",57:"62a1276f",67:"59b1a96c",108:"3dd307b5",113:"cdf0eeb2",116:"5b254f70",168:"feaee7f3",225:"8a8faf8d",291:"21dc2778",454:"a4d3e054",514:"1be78505",535:"1222ea4e",594:"cbe663fe",683:"8156e19a",684:"cb1e72f9",784:"ba3d4959",799:"7333c691",832:"fb313d4e",865:"e19c288b",918:"17896441",920:"1a4e3797",966:"d459b1c4",969:"0ab078a9"}[e]||e)+"."+{8:"9751aa02",53:"c45c3ca0",57:"732e44fe",67:"79c5818c",108:"7b464df0",113:"29f89fc3",116:"287f094d",168:"700d4636",176:"1f8f2d9b",225:"2ff78836",291:"c3cad2a2",426:"97069429",454:"2c177800",514:"fb48f26a",535:"93c74363",594:"8fc7d46f",683:"5e01ccd6",684:"c0a429c9",784:"86bd32f7",799:"d4a3b177",832:"246c2a2a",865:"8ce43523",894:"1afcfcdd",918:"35ffcf9d",920:"ca05490f",945:"62d4a71f",966:"7a1fface",969:"b12188c8",972:"b9e804c8"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a={},o="tinyorm.org:",c.l=(e,t,r,f)=>{if(a[e])a[e].push(t);else{var n,d;if(void 0!==r)for(var i=document.getElementsByTagName("script"),b=0;b{n.onerror=n.onload=null,clearTimeout(s);var o=a[e];if(delete a[e],n.parentNode&&n.parentNode.removeChild(n),o&&o.forEach((e=>e(r))),t)return t(r)},s=setTimeout(l.bind(null,void 0,{type:"timeout",target:n}),12e4);n.onerror=l.bind(null,n.onerror),n.onload=l.bind(null,n.onload),d&&document.head.appendChild(n)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.p="/",c.gca=function(e){return e={17896441:"918",e3ac21cb:"8","935f2afb":"53","62a1276f":"57","59b1a96c":"67","3dd307b5":"108",cdf0eeb2:"113","5b254f70":"116",feaee7f3:"168","8a8faf8d":"225","21dc2778":"291",a4d3e054:"454","1be78505":"514","1222ea4e":"535",cbe663fe:"594","8156e19a":"683",cb1e72f9:"684",ba3d4959:"784","7333c691":"799",fb313d4e:"832",e19c288b:"865","1a4e3797":"920",d459b1c4:"966","0ab078a9":"969"}[e]||e,c.p+c.u(e)},(()=>{var e={303:0,532:0};c.f.j=(t,r)=>{var a=c.o(e,t)?e[t]:void 0;if(0!==a)if(a)r.push(a[2]);else if(/^(303|532)$/.test(t))e[t]=0;else{var o=new Promise(((r,o)=>a=e[t]=[r,o]));r.push(a[2]=o);var f=c.p+c.u(t),n=new Error;c.l(f,(r=>{if(c.o(e,t)&&(0!==(a=e[t])&&(e[t]=void 0),a)){var o=r&&("load"===r.type?"missing":r.type),f=r&&r.target&&r.target.src;n.message="Loading chunk "+t+" failed.\n("+o+": "+f+")",n.name="ChunkLoadError",n.type=o,n.request=f,a[1](n)}}),"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var a,o,f=r[0],n=r[1],d=r[2],i=0;if(f.some((t=>0!==e[t]))){for(a in n)c.o(n,a)&&(c.m[a]=n[a]);if(d)var b=d(c)}for(t&&t(r);igtag("config","AW-989655383"),gtag("event","conversion",{send_to:"AW-989655383/vDYzCM--ks4DENfi89cD"}) - +
-

Building: Hello world

Introduction

We will try to create the simplest working console application, in the terminal with the CMake and in the QtCreator IDE with the qmake build systems.

The HelloWorld example also expects the following folders structure, let's create them.

cd 
mkdir HelloWorld/HelloWorld
cd HelloWorld

Prepare SQLite 3 database

The easiest way to demonstrate the HelloWorld example will be with a SQLite 3 database.

Execute the following command in the terminal to create and insert two rows into the SQLite 3 database.

sqlite3 HelloWorld.sqlite3 "
create table posts(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR NOT NULL);
insert into posts values(1, 'First Post');
insert into posts values(2, 'Second Post');
select * from posts;"

Install dependencies

First, install the vcpkg package manager as is described here.

The range-v3 and tabulate libraries are required dependencies because TinyORM uses them in header files, you have to install them before you can use TinyORM. The tabulate library is only needed in the tom migrations it's used by the migrate:status command.

There are two ways how to install the range-v3 and tabulate libraries using vcpkg.

Using vcpkg.json (manifest mode)

Create a vcpkg.json file with the following content. CMake example below uses this method.

cd HelloWorld
vim vcpkg.json
vcpkg.json
{
"$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",
"name": "tinyorm-helloworld",
"version-semver": "0.1.0",
"description": "Hello world console application for TinyORM C++ library",
"homepage": "https://github.com/silverqx/TinyORM",
"documentation": "https://www.tinyorm.org/building/hello-world",
"maintainers": "Silver Zachara <silver.zachara@gmail.com>",
"supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",
"dependencies": [
"range-v3",
"tabulate"
]
}
note

Only CMake via the toolchain file supports this method.

Using vcpkg install (manually)

This method can be used with both CMake and qmake.

cd ../../vcpkg

vcpkg search range-v3
vcpkg search tabulate
vcpkg install range-v3 tabulate
vcpkg list

Source code

Let's start in the HelloWorld project folder.

cd /HelloWorld/HelloWorld

Create main.cpp source file.

vim main.cpp
tip

To paste a source code correctly in vim, press Shift + p.

And paste the following code.

main.cpp
#include <QCoreApplication>
#include <QDebug>

#ifdef _WIN32
# include <qt_windows.h>
#endif

#include <orm/db.hpp>

using Orm::DB;

int main(int argc, char *argv[])
{
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
// SetConsoleOutputCP(1250);
#endif

/* Needed from Qt v6.5.3 to avoid:
qt.core.qobject.connect: QObject::connect(QObject, Unknown): invalid nullptr parameter */
QCoreApplication app(argc, argv);

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QSQLITE"},
{"database", qEnvironmentVariable("TINYORM_HELLOWORLD_DB_SQLITE_DATABASE",
"../../HelloWorld.sqlite3")},
{"check_database_exists", true},
});

auto posts = DB::select("select * from posts");

while(posts.next())
qDebug() << posts.value("id").toULongLong()
<< posts.value("name").toString();
}
caution

The QSqlDatabase depends on QCoreApplication from Qt v6.5.3 so you must create the QCoreApplication instance before you will call anything from the TinyORM library. 🫤 The change was made here.

Hello world with CMake

Create a folder for the CMake build.

cd ..
mkdir HelloWorld-builds-cmake/build-debug

cd HelloWorld

CMake project

Create CMakeLists.txt file with the following content.

cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)

project(HelloWorld LANGUAGES CXX)

# build tree
list(APPEND CMAKE_PREFIX_PATH "/TinyORM/TinyORM-builds-cmake/build-debug")

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(HelloWorld
main.cpp
)

find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)
find_package(TinyOrm 0.37.0 CONFIG REQUIRED)

target_link_libraries(HelloWorld
PRIVATE
Qt${QT_VERSION_MAJOR}::Core
TinyOrm::TinyOrm
)

FetchContent

If you don't have cloned and built the TinyORM library, or you want to quickly try TinyORM without wasting time with cloning and building the TinyORM library, then you can use CMake's FetchContent module that will do all of this for you.

Instead of providing a path by the CMAKE_PREFIX_PATH (or using the User Package Registry) like in the example below:

# build tree
list(APPEND CMAKE_PREFIX_PATH "/TinyORM/TinyORM-builds-cmake/build-debug")

You can use the FetchContent module like in the following example.

cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)

project(HelloWorld LANGUAGES CXX)

# FetchContent method
include(FetchContent)
FetchContent_Declare(TinyOrm
GIT_REPOSITORY https://github.com/silverqx/TinyORM.git
GIT_TAG origin/main
OVERRIDE_FIND_PACKAGE
)
# Here you can configure TinyORM CMake options
set(MYSQL_PING OFF)
set(TOM_EXAMPLE ON)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(HelloWorld
main.cpp
)

find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)
find_package(TinyOrm 0.37.0 CONFIG REQUIRED)

target_link_libraries(HelloWorld
PRIVATE
Qt${QT_VERSION_MAJOR}::Core
TinyOrm::TinyOrm
)

How FetchContent module works

The FetchContent_Declare command is like calling the git clone inside the build folder and then adding a cloned folder in a similar way as the add_subdirectory(<cloned_folder>) command does.

The FetchContent_MakeAvailable(<package>) internally calls the find_package(<package>) command or if you pass the OVERRIDE_FIND_PACKAGE argument, then you don't have to call the the FetchContent_MakeAvailable, but you must call the find_package(<package> x.y.z CONFIG REQUIRED) command manually.

info

An advantage of the OVERRIDE_FIND_PACKAGE argument is that you can call the find_package command much later, and you can insert additional configurations between.

Build Hello world

Now you are ready to configure HelloWorld CMake application.

cd ../HelloWorld-builds-cmake/build-debug
cmake.exe `
-S "/HelloWorld/HelloWorld" `
-B "/HelloWorld/HelloWorld-builds-cmake/build-debug" `
-G 'Ninja' `
-D CMAKE_BUILD_TYPE:STRING='Debug' `
-D CMAKE_TOOLCHAIN_FILE:FILEPATH="/vcpkg/scripts/buildsystems/vcpkg.cmake" `
-D CMAKE_INSTALL_PREFIX:PATH="/tmp/HelloWorld"

And build.

cmake --build . --target all
tip

Enable the TINYORM_STRICT_MODE environment variable to produce better code and to follow good code practices.

Execute Hello world

Do not forget to add TinyOrm0d.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so HelloWorld application can find it during execution, as is described here.

$env:Path = "\TinyORM\TinyORM-builds-cmake\build-debug;" + $env:Path

Execute HelloWorld example.

.\HelloWorld.exe

The output will look like this.

Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts
1 "First Post"
2 "Second Post"

Hello world with qmake

Create a folder for the qmake build.

cd /HelloWorld

mkdir HelloWorld-builds-qmake

The source code is the same as for the HelloWorld CMake example.

qmake project

Create HelloWorld.pro qmake file with the following content.

cd HelloWorld
vim HelloWorld.pro
tip

To paste a source code correctly in vim, press Shift + p.

HelloWorld.pro
QT -= gui

TEMPLATE = app

CONFIG *= cmdline

DEFINES *= PROJECT_TINYORM_HELLOWORLD

SOURCES += $$PWD/main.cpp

# Auto-configure TinyORM library 🔥
include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)
caution

The exact folders structure is crucial in this example because the paths to the TinyORM source and build folders are relative.

caution

Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

Auto-configure using .qmake.conf and .env

If you want to have properly configured DEFINES (C preprocessor macros) or have Qt headers marked as system headers, then you need to specify a path to the TinyORM qmake features (.prf files) which handle this correctly; this path is provided by the QMAKEFEATURES variable and can only be set in the .qmake.conf file.

tip

Read the Consume TinyOrm library (qmake) section, as everything that is described in that section applies here as well.

Create the .qmake.conf file in the HelloWorld project root folder with the following content.

.qmake.conf
# Path to the PARENT folder of the TinyORM source folder
TINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)
# To find .env and .env.$$QMAKE_PLATFORM files
TINY_DOTENV_ROOT = $$PWD
# Path to the current build tree (used to guess the TinyORM build tree)
#TINY_BUILD_TREE = $$shadowed($$PWD)

# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants
QMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)

Then, create a .env.(win32|unix|mingw) file in the HelloWorld project root folder with the following content.

# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro
# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

# Path to the TinyORM build folder
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)

# Path to the vcpkg - range-v3
# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty
TINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)
TINY_VCPKG_TRIPLET = x64-windows

# Enable ccache wrapper
#CONFIG *= tiny_ccache_win32

Don't forget to update the TINYORM_BUILD_TREE and TINY_VCPKG_ROOT folder paths to your needs if you are not using the recommended Folders structure.

You can use the Partial guessing of the TINYORM_BUILD_TREE if you don't like to specify it manually. Just comment out the TINYORM_BUILD_TREE and uncomment the TINY_BUILD_TREE = $$shadowed($$PWD) in the .qmake.conf file.

tip

You can entirely avoid the .env files, just move the TINYORM_BUILD_TREE to the .qmake.conf or remove it by help of Partial guessing of the TINYORM_BUILD_TREE and set the VCPKG_ROOT environment variable at system level as is described in Set up vcpkg environment.

info

Configuring by the .qmake.conf and .env files has one big advantage, which is that you don't have to modify the project files.

Build Hello world

tip

I recommend creating a new Session in the QtCreator IDE as is described here.

Now you can open the HelloWorld.pro project in the QtCreator IDE.

This will open the Configure Project tab, select some kit and update build folder paths to meet our folders structure or like you want.

HelloWorld - QtCreator - Configure Project
tip

You can force the QtCreator to generate a build folders structure as is described here.

You are ready to configure build options, hit Ctrl+5 to open Project Settings tab and select Build in the left sidebar to open the Build Settings, it should look similar to the following picture.

HelloWorld - QtCreator - Build Settings

Disable QML debugging and profiling and Qt Quick Compiler, they are not used.

In the left sidebar open Dependencies and check TinyORM project and Synchronize configuration, this setting ensures that the current project will be rebuilt correctly when the TinyORM library source code changes.

Everything is ready to build, you can press Ctrl+b to build the project.

Execute Hello world

The QtCreator takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the LD_LIBRARY_PATH on Linux.

The only thing you might want to change is to run the HelloWorld example in the new terminal window. To do so, hit Ctrl+5 to open the Project Settings tab and select Run in the left sidebar to open the Run Settings, then in the Run section select the Run in terminal checkbox.

To execute the HelloWorld example press Ctrl + r.

The output will look like this.

Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts
1 "First Post"
2 "Second Post"
- +

Building: Hello world

Introduction

We will try to create the simplest working console application, in the terminal with the CMake and in the QtCreator IDE with the qmake build systems.

The HelloWorld example also expects the following folders structure, let's create them.

cd 
mkdir HelloWorld/HelloWorld
cd HelloWorld

Prepare SQLite 3 database

The easiest way to demonstrate the HelloWorld example will be with a SQLite 3 database.

Execute the following command in the terminal to create and insert two rows into the SQLite 3 database.

sqlite3 HelloWorld.sqlite3 "
create table posts(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR NOT NULL);
insert into posts values(1, 'First Post');
insert into posts values(2, 'Second Post');
select * from posts;"

Install dependencies

First, install the vcpkg package manager as is described here.

The range-v3 and tabulate libraries are required dependencies because TinyORM uses them in header files, you have to install them before you can use TinyORM. The tabulate library is only needed in the tom migrations it's used by the migrate:status command.

There are two ways how to install the range-v3 and tabulate libraries using vcpkg.

Using vcpkg.json (manifest mode)

Create a vcpkg.json file with the following content. CMake example below uses this method.

cd HelloWorld
vim vcpkg.json
vcpkg.json
{
"$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",
"name": "tinyorm-helloworld",
"version-semver": "0.1.0",
"description": "Hello world console application for TinyORM C++ library",
"homepage": "https://github.com/silverqx/TinyORM",
"documentation": "https://www.tinyorm.org/building/hello-world",
"maintainers": "Silver Zachara <silver.zachara@gmail.com>",
"supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",
"dependencies": [
"range-v3",
"tabulate"
]
}
note

Only CMake via the toolchain file supports this method.

Using vcpkg install (manually)

This method can be used with both CMake and qmake.

cd ../../vcpkg

vcpkg search range-v3
vcpkg search tabulate
vcpkg install range-v3 tabulate
vcpkg list

Source code

Let's start in the HelloWorld project folder.

cd /HelloWorld/HelloWorld

Create main.cpp source file.

vim main.cpp
tip

To paste a source code correctly in vim, press Shift + p.

And paste the following code.

main.cpp
#include <QCoreApplication>
#include <QDebug>

#ifdef _WIN32
# include <qt_windows.h>
#endif

#include <orm/db.hpp>

using Orm::DB;

int main(int argc, char *argv[])
{
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
// SetConsoleOutputCP(1250);
#endif

/* Needed from Qt v6.5.3 to avoid:
qt.core.qobject.connect: QObject::connect(QObject, Unknown): invalid nullptr parameter */
QCoreApplication app(argc, argv);

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QSQLITE"},
{"database", qEnvironmentVariable("TINYORM_HELLOWORLD_DB_SQLITE_DATABASE",
"../../HelloWorld.sqlite3")},
{"check_database_exists", true},
});

auto posts = DB::select("select * from posts");

while(posts.next())
qDebug() << posts.value("id").toULongLong()
<< posts.value("name").toString();
}
caution

The QSqlDatabase depends on QCoreApplication from Qt v6.5.3 so you must create the QCoreApplication instance before you will call anything from the TinyORM library. 🫤 The change was made here.

Hello world with CMake

Create a folder for the CMake build.

cd ..
mkdir HelloWorld-builds-cmake/build-debug

cd HelloWorld

CMake project

Create CMakeLists.txt file with the following content.

cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)

project(HelloWorld LANGUAGES CXX)

# build tree
list(APPEND CMAKE_PREFIX_PATH "/TinyORM/TinyORM-builds-cmake/build-debug")

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(HelloWorld
main.cpp
)

find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)
find_package(TinyOrm 0.37.1 CONFIG REQUIRED)

target_link_libraries(HelloWorld
PRIVATE
Qt${QT_VERSION_MAJOR}::Core
TinyOrm::TinyOrm
)

FetchContent

If you don't have cloned and built the TinyORM library, or you want to quickly try TinyORM without wasting time with cloning and building the TinyORM library, then you can use CMake's FetchContent module that will do all of this for you.

Instead of providing a path by the CMAKE_PREFIX_PATH (or using the User Package Registry) like in the example below:

# build tree
list(APPEND CMAKE_PREFIX_PATH "/TinyORM/TinyORM-builds-cmake/build-debug")

You can use the FetchContent module like in the following example.

cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)

project(HelloWorld LANGUAGES CXX)

# FetchContent method
include(FetchContent)
FetchContent_Declare(TinyOrm
GIT_REPOSITORY https://github.com/silverqx/TinyORM.git
GIT_TAG origin/main
OVERRIDE_FIND_PACKAGE
)
# Here you can configure TinyORM CMake options
set(MYSQL_PING OFF)
set(TOM_EXAMPLE ON)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(HelloWorld
main.cpp
)

find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)
find_package(TinyOrm 0.37.1 CONFIG REQUIRED)

target_link_libraries(HelloWorld
PRIVATE
Qt${QT_VERSION_MAJOR}::Core
TinyOrm::TinyOrm
)

How FetchContent module works

The FetchContent_Declare command is like calling the git clone inside the build folder and then adding a cloned folder in a similar way as the add_subdirectory(<cloned_folder>) command does.

The FetchContent_MakeAvailable(<package>) internally calls the find_package(<package>) command or if you pass the OVERRIDE_FIND_PACKAGE argument, then you don't have to call the the FetchContent_MakeAvailable, but you must call the find_package(<package> x.y.z CONFIG REQUIRED) command manually.

info

An advantage of the OVERRIDE_FIND_PACKAGE argument is that you can call the find_package command much later, and you can insert additional configurations between.

Build Hello world

Now you are ready to configure HelloWorld CMake application.

cd ../HelloWorld-builds-cmake/build-debug
cmake.exe `
-S "/HelloWorld/HelloWorld" `
-B "/HelloWorld/HelloWorld-builds-cmake/build-debug" `
-G 'Ninja' `
-D CMAKE_BUILD_TYPE:STRING='Debug' `
-D CMAKE_TOOLCHAIN_FILE:FILEPATH="/vcpkg/scripts/buildsystems/vcpkg.cmake" `
-D CMAKE_INSTALL_PREFIX:PATH="/tmp/HelloWorld"

And build.

cmake --build . --target all
tip

Enable the TINYORM_STRICT_MODE environment variable to produce better code and to follow good code practices.

Execute Hello world

Do not forget to add TinyOrm0d.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so HelloWorld application can find it during execution, as is described here.

$env:Path = "\TinyORM\TinyORM-builds-cmake\build-debug;" + $env:Path

Execute HelloWorld example.

.\HelloWorld.exe

The output will look like this.

Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts
1 "First Post"
2 "Second Post"

Hello world with qmake

Create a folder for the qmake build.

cd /HelloWorld

mkdir HelloWorld-builds-qmake

The source code is the same as for the HelloWorld CMake example.

qmake project

Create HelloWorld.pro qmake file with the following content.

cd HelloWorld
vim HelloWorld.pro
tip

To paste a source code correctly in vim, press Shift + p.

HelloWorld.pro
QT -= gui

TEMPLATE = app

CONFIG *= cmdline

DEFINES *= PROJECT_TINYORM_HELLOWORLD

SOURCES += $$PWD/main.cpp

# Auto-configure TinyORM library 🔥
include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)
caution

The exact folders structure is crucial in this example because the paths to the TinyORM source and build folders are relative.

caution

Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

Auto-configure using .qmake.conf and .env

If you want to have properly configured DEFINES (C preprocessor macros) or have Qt headers marked as system headers, then you need to specify a path to the TinyORM qmake features (.prf files) which handle this correctly; this path is provided by the QMAKEFEATURES variable and can only be set in the .qmake.conf file.

tip

Read the Consume TinyOrm library (qmake) section, as everything that is described in that section applies here as well.

Create the .qmake.conf file in the HelloWorld project root folder with the following content.

.qmake.conf
# Path to the PARENT folder of the TinyORM source folder
TINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)
# To find .env and .env.$$QMAKE_PLATFORM files
TINY_DOTENV_ROOT = $$PWD
# Path to the current build tree (used to guess the TinyORM build tree)
#TINY_BUILD_TREE = $$shadowed($$PWD)

# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants
QMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)

Then, create a .env.(win32|unix|mingw) file in the HelloWorld project root folder with the following content.

# Names and values of these qmake variables are crucial, they are used in HelloWorld.pro
# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

# Path to the TinyORM build folder
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)

# Path to the vcpkg - range-v3
# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty
TINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)
TINY_VCPKG_TRIPLET = x64-windows

# Enable ccache wrapper
#CONFIG *= tiny_ccache_win32

Don't forget to update the TINYORM_BUILD_TREE and TINY_VCPKG_ROOT folder paths to your needs if you are not using the recommended Folders structure.

You can use the Partial guessing of the TINYORM_BUILD_TREE if you don't like to specify it manually. Just comment out the TINYORM_BUILD_TREE and uncomment the TINY_BUILD_TREE = $$shadowed($$PWD) in the .qmake.conf file.

tip

You can entirely avoid the .env files, just move the TINYORM_BUILD_TREE to the .qmake.conf or remove it by help of Partial guessing of the TINYORM_BUILD_TREE and set the VCPKG_ROOT environment variable at system level as is described in Set up vcpkg environment.

info

Configuring by the .qmake.conf and .env files has one big advantage, which is that you don't have to modify the project files.

Build Hello world

tip

I recommend creating a new Session in the QtCreator IDE as is described here.

Now you can open the HelloWorld.pro project in the QtCreator IDE.

This will open the Configure Project tab, select some kit and update build folder paths to meet our folders structure or like you want.

HelloWorld - QtCreator - Configure Project
tip

You can force the QtCreator to generate a build folders structure as is described here.

You are ready to configure build options, hit Ctrl+5 to open Project Settings tab and select Build in the left sidebar to open the Build Settings, it should look similar to the following picture.

HelloWorld - QtCreator - Build Settings

Disable QML debugging and profiling and Qt Quick Compiler, they are not used.

In the left sidebar open Dependencies and check TinyORM project and Synchronize configuration, this setting ensures that the current project will be rebuilt correctly when the TinyORM library source code changes.

Everything is ready to build, you can press Ctrl+b to build the project.

Execute Hello world

The QtCreator takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the LD_LIBRARY_PATH on Linux.

The only thing you might want to change is to run the HelloWorld example in the new terminal window. To do so, hit Ctrl+5 to open the Project Settings tab and select Run in the left sidebar to open the Run Settings, then in the Run section select the Run in terminal checkbox.

To execute the HelloWorld example press Ctrl + r.

The output will look like this.

Executed prepared query (6ms, -1 results, 0 affected, tinyorm_default) : select * from posts
1 "First Post"
2 "Second Post"
+ \ No newline at end of file diff --git a/building/migrations.html b/building/migrations.html index 99cec31b3..8888517e6 100644 --- a/building/migrations.html +++ b/building/migrations.html @@ -14,13 +14,13 @@ - +
-

Building: Migrations

Introduction

We will try to create a working migrations console application called as tom in the terminal with the CMake and in the QtCreator IDE with the qmake build systems.

The tom console application also expects the following folders structure, let's create them.

cd 
mkdir tom/tom
cd tom

TinyORM source tree contains the tom example application, you can inspire or look at the source code. Also, TinyORM unit tests use a tom migrations internally to create the database structure, internally called as the tom migrations for unit tests.

All these three console applications the tom example, tom migrations for unit tests, and the application described in this tutorial have practically identical source code (the main.cpp file).

note

The tom is able to generate DDL queries for all the supported databases databases.

info

You can see the Tom showcase image of how the resulting tom console application will look like.

Install dependencies

First, install the vcpkg package manager as is described here.

The range-v3 and tabulate libraries are required dependencies because TinyORM uses them in header files, you have to install them before you can use TinyORM. The tabulate library is only needed in the tom migrations it's used by the migrate:status command.

There are two ways how to install the range-v3 and tabulate libraries using vcpkg.

Also, don't forget to build the TinyORM library with the tom source code enabled (it's enabled by default) as is described here.

Using vcpkg.json (manifest mode)

Create a vcpkg.json file with the following content. CMake example below uses this method.

cd tom
vim vcpkg.json
vcpkg.json
{
"$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",
"name": "tom",
"version-semver": "0.1.0",
"description": "Tom console application for TinyORM C++ library",
"homepage": "https://github.com/silverqx/TinyORM",
"documentation": "https://www.tinyorm.org/building/migrations",
"maintainers": "Silver Zachara <silver.zachara@gmail.com>",
"supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",
"dependencies": [
"range-v3",
"tabulate"
]
}
note

Only CMake via the toolchain file supports this method.

Using vcpkg install (manually)

This method can be used with both CMake and qmake.

cd ../../vcpkg

vcpkg search range-v3
vcpkg search tabulate
vcpkg install range-v3 tabulate
vcpkg list

Source code

Let's start in the tom project folder.

cd /tom/tom

Main file

Create main.cpp source file.

vim main.cpp
tip

To paste a source code correctly in vim, press Shift + p.

And paste the following code.

main.cpp
#include <orm/db.hpp>

#include <tom/application.hpp>

#include "migrations/2014_10_12_000000_create_posts_table.hpp"

#include "seeders/databaseseeder.hpp"

using Orm::DatabaseManager;
using Orm::DB;

using TomApplication = Tom::Application;

using namespace Migrations; // NOLINT(google-build-using-namespace)
using namespace Seeders; // NOLINT(google-build-using-namespace)

/*! Create the database manager instance and add a database connection. */
std::shared_ptr<DatabaseManager> setupDatabaseManager();

/*! C++ main function. */
int main(int argc, char *argv[])
{
try {
// Ownership of the shared_ptr()
auto db = setupDatabaseManager();

return TomApplication(argc, argv, std::move(db), "TOM_EXAMPLE_ENV")
.migrations<CreatePostsTable>()
.seeders<DatabaseSeeder>()
// Fire it up 🔥🚀✨
.run();

} catch (const std::exception &e) {

TomApplication::logException(e);
}

return EXIT_FAILURE;
}

std::shared_ptr<DatabaseManager> setupDatabaseManager()
{
using namespace Orm::Constants; // NOLINT(google-build-using-namespace)

// Ownership of the shared_ptr()
return DB::create({
{driver_, QMYSQL},
{host_, qEnvironmentVariable("DB_MYSQL_HOST", H127001)},
{port_, qEnvironmentVariable("DB_MYSQL_PORT", P3306)},
{database_, qEnvironmentVariable("DB_MYSQL_DATABASE", EMPTY)},
{username_, qEnvironmentVariable("DB_MYSQL_USERNAME", EMPTY)},
{password_, qEnvironmentVariable("DB_MYSQL_PASSWORD", EMPTY)},
{charset_, qEnvironmentVariable("DB_MYSQL_CHARSET", UTF8MB4)},
{collation_, qEnvironmentVariable("DB_MYSQL_COLLATION", UTF8MB40900aici)},
{timezone_, TZ00},
/* Specifies what time zone all QDateTime-s will have, the overridden default is
the Qt::UTC, set to the Qt::LocalTime or QtTimeZoneType::DontConvert to use
the system local time. */
{qt_timezone, QVariant::fromValue(Qt::UTC)},
{strict_, true},
},
QStringLiteral("tinyorm_tom_mysql")); // shell:connection
}
tip

If you have defined more database connections then you can tag the lines with the database connection names with the // shell:connection comment and this connection names will be provided to the bash, zsh, pwsh completions for the --database= option 😎, example.

Migrations

If you have already built the tom application then you can generate a migrations using the make:migration command 😎.

tom make:migration create_posts_table

Below is the expected folders structure for the migrations. The migrations.pri file is used only by the qmake build system and is not needed with CMake builds.

tom/
└── database/
├── migrations/
├── seeders/
├── migrations.pri
└── seeders.pri

Let's create the first migration manually.

mkdir database/migrations

vim database/migrations/2014_10_12_000000_create_posts_table.hpp

And paste the following code.

database/migrations/2014_10_12_000000_create_posts_table.hpp
#pragma once

#include <tom/migration.hpp>

namespace Migrations
{

struct CreatePostsTable : Migration
{
/*! Filename of the migration file. */
T_MIGRATION

/*! Run the migrations. */
void up() const override
{
Schema::create("posts", [](Blueprint &table)
{
table.id();

table.string(NAME);
table.timestamps();
});
}

/*! Reverse the migrations. */
void down() const override
{
Schema::dropIfExists("posts");
}
};

} // namespace Migrations
tip

The TinyORM source tree contains the CreatePostsTable example migration that also acts as the full-fledged example migration. It has defined and also nicely commented all possible features that migration classes can use or define.

info

If you want, you can also build the tom application without the migrations, simply comment out the migrations method and the corresponding #include "migrations/xyz.hpp" files.

Seeders

If you have already built the tom application then you can generate a seeder using the make:seeder command 😎.

tom make:seeder PostSeeder

The expected folders structure is described a few paragraphs above. The seeders.pri file is used only by the qmake build system and is not needed with CMake builds.

Let's create the root seeder class manually.

mkdir database/seeders

vim database/seeders/databaseseeder.hpp

And paste the following code.

database/seeders/databaseseeder.hpp
#pragma once

#include <tom/seeder.hpp>

namespace Seeders
{

/*! Main database seeder. */
struct DatabaseSeeder : Seeder
{
/*! Run the database seeders. */
void run() override
{
DB::table("posts")->insert({
{{"name", "1. post"}},
{{"name", "2. post"}},
});
}
};

} // namespace Seeders
tip

The TinyORM source tree contains the DatabaseSeeder root seeder example class that also acts as the full-fledged example seeder. It has defined and also nicely commented all possible features that seeder classes can use or define.

tip

You can create more seeder classes like this and use the call<>() method to invoke them as is described in the Calling Additional Seeders section.

Migrations with CMake

Create a folder for the CMake build.

cd ..
mkdir tom-builds-cmake/build-debug

cd tom

CMake project

Create CMakeLists.txt file with the following content. I leave the comments in the CMakeLists.txt file because it's not as simple as the Hello world example; to make it clear what's going on.

CMakeLists.txt
cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)

# Specify the C++ standard
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# Initialize variables
# ---

set(Tom_ns tom)
set(Tom_target tom)

file(REAL_PATH "../../TinyORM" TinyMainDir)

set(TinyOrmSourceDir "${TinyMainDir}/TinyORM")
set(TinyOrmBuildDir "${TinyMainDir}/TinyORM-builds-cmake/build-debug")

# TinyORM CMake modules (needed to set the executable version and RC file on Windows)
list(APPEND CMAKE_MODULE_PATH "${TinyOrmSourceDir}/cmake/CommonModules")

# build tree
list(APPEND CMAKE_PREFIX_PATH "${TinyOrmBuildDir}")

# Initialize Project Version
# ---

include(TinyHelpers)
tiny_read_version(TINY_VERSION
TINY_VERSION_MAJOR TINY_VERSION_MINOR TINY_VERSION_PATCH TINY_VERSION_TWEAK
VERSION_HEADER "${TinyOrmSourceDir}/tom/include/tom/version.hpp"
PREFIX TINYTOM
HEADER_FOR "${Tom_ns}"
)

# Basic project
# ---

project(${Tom_ns}
DESCRIPTION "Tom console application for TinyORM C++ library"
HOMEPAGE_URL "https://www.tinyorm.org"
LANGUAGES CXX
VERSION ${TINY_VERSION}
)

# Tom command-line application
# ---

add_executable(${Tom_target}
main.cpp
)
add_executable(${Tom_ns}::${Tom_target} ALIAS ${Tom_target})

# Tom command-line application specific configuration
# ---

set_target_properties(${Tom_target}
PROPERTIES
C_VISIBILITY_PRESET "hidden"
CXX_VISIBILITY_PRESET "hidden"
VISIBILITY_INLINES_HIDDEN YES
VERSION ${PROJECT_VERSION}
)

target_include_directories(${Tom_target}
PRIVATE "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/database>"
)

# Tom command-line application defines
# ---

target_compile_definitions(${Tom_target}
PRIVATE
PROJECT_TOM
)

# Windows resource and manifest files
# ---

# Find icons, tom/version.hpp, and Windows manifest file for MinGW
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
tiny_set_rc_flags("-I \"${TinyOrmSourceDir}/tom/resources\"")
endif()

include(TinyResourceAndManifest)
tiny_resource_and_manifest(${Tom_target}
OUTPUT_DIR "${TINY_BUILD_GENDIR}/tmp/"
RESOURCES_DIR "${TinyOrmSourceDir}/tom/resources"
)

# Resolve and link dependencies
# ---

find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)
find_package(TinyOrm 0.37.0 CONFIG REQUIRED)

# Unconditional dependencies
target_link_libraries(${Tom_target}
PRIVATE
Qt${QT_VERSION_MAJOR}::Core
TinyOrm::TinyOrm
)

Build migrations

Now you are ready to configure tom CMake application. Don't forget to prepare the build environment with the qtenv6.ps1 command if you are building with the msvc.

cd ../tom-builds-cmake/build-debug
cmake.exe `
-S "/tom/tom" `
-B "/tom/tom-builds-cmake/build-debug" `
-G 'Ninja' `
-D CMAKE_BUILD_TYPE:STRING='Debug' `
-D CMAKE_TOOLCHAIN_FILE:FILEPATH="/vcpkg/scripts/buildsystems/vcpkg.cmake" `
-D CMAKE_INSTALL_PREFIX:PATH="/tmp/tom"

And build.

cmake --build . --target all

Execute migrations

Do not forget to add TinyOrm0d.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so tom application can find it during execution, as is described here.

$env:Path = "\TinyORM\TinyORM-builds-cmake\build-debug;" + $env:Path

Execute tom application.

.\tom.exe migrate:status

The output will look something like this.

Tom migrations - migrate:status command output

See also the final thoughts on how to verify the tom executable file properties.

Happy migrating 🎉👌

Migrations with qmake

Create a folder for the qmake build.

cd /tom

mkdir tom-builds-qmake

The source code is the same as for the Migrations with CMake console application.

qmake project

Create tom.pro qmake file with the following content.

cd tom
vim tom.pro
tip

To paste a source code correctly in vim, press Shift + p.

tom.pro
QT -= gui

TEMPLATE = app
TARGET = tom

CONFIG *= cmdline

DEFINES *= PROJECT_TOM

SOURCES += $$PWD/main.cpp

# Database migrations
include($$PWD/database/migrations.pri)
# Database seeders
include($$PWD/database/seeders.pri)

# Auto-configure TinyORM library for the migrations purposes 🔥
include($$TINY_MAIN_DIR/TinyORM/qmake/tom.pri)
caution

The exact folders structure is crucial in this example because the paths to the TinyORM source and build folders are relative.

caution

Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

Auto-configure using .qmake.conf and .env

If you want to have properly configured DEFINES (C preprocessor macros), have Qt headers marked as system headers, or eg. have properly set properties of an executable file such as version and description, then you need to specify a path to the TinyORM qmake features (.prf files) which handle this correctly; this path is provided by the QMAKEFEATURES variable and can only be set in the .qmake.conf file.

tip

Read the Consume TinyOrm library (qmake) section, as everything that is described in that section applies here as well.

Create the .qmake.conf file in the tom application root folder with the following content.

.qmake.conf
# Path to the PARENT folder of the TinyORM source folder
TINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)
# To find .env and .env.$$QMAKE_PLATFORM files
TINY_DOTENV_ROOT = $$PWD
# Path to the current build tree (used to guess the TinyORM build tree)
#TINY_BUILD_TREE = $$shadowed($$PWD)

# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants
QMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)

Then, create a .env.(win32|unix|mingw) file in the tom application root folder with the following content.

# Names and values of these qmake variables are crucial, they are used in the tom.pro
# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

# Path to the TinyORM build folder
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)

# Path to the vcpkg - range-v3 and tabulate
# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty
TINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)
TINY_VCPKG_TRIPLET = x64-windows

# Enable ccache wrapper
#CONFIG *= tiny_ccache_win32

Don't forget to update the TINYORM_BUILD_TREE and TINY_VCPKG_ROOT folder paths to your needs if you are not using the recommended Folders structure.

You can use the Partial guessing of the TINYORM_BUILD_TREE if you don't like to specify it manually. Just comment out the TINYORM_BUILD_TREE and uncomment the TINY_BUILD_TREE = $$shadowed($$PWD) in the .qmake.conf file.

tip

You can entirely avoid the .env files, just move the TINYORM_BUILD_TREE to the .qmake.conf or remove it by help of Partial guessing of the TINYORM_BUILD_TREE and set the VCPKG_ROOT environment variable at system level as is described in Set up vcpkg environment.

info

Configuring by the .qmake.conf and .env files has one big advantage, which is that you don't have to modify the project files.

Migrations source files

Create database/migrations.pri file and paste the following code.

database/migrations.pri
INCLUDEPATH *= $$PWD

HEADERS += \
$$PWD/migrations/2014_10_12_000000_create_posts_table.hpp \

Seeders source files

Create database/seeders.pri file and paste the following code.

database/seeders.pri
INCLUDEPATH *= $$PWD

HEADERS += \
$$PWD/seeders/databaseseeder.hpp \

Build migrations

tip

I recommend creating a new Session in the QtCreator IDE as is described here.

Now you can open the tom.pro project in the QtCreator IDE.

This will open the Configure Project tab, select some kit and update build folder paths to meet our folders structure or like you want.

tom - QtCreator - Configure Project
tip

You can force the QtCreator to generate a build folders structure as is described here.

You are ready to configure build options, hit Ctrl+5 to open Project Settings tab and select Build in the left sidebar to open the Build Settings, it should look similar to the following picture.

tom - QtCreator - Build Settings

Disable QML debugging and profiling and Qt Quick Compiler, they are not used.

In the left sidebar open Dependencies and check TinyORM project and Synchronize configuration, this setting ensures that the current project will be rebuilt correctly when the TinyORM library source code changes.

Everything is ready to build, you can press Ctrl+b to build the project.

Execute migrations

The QtCreator takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the LD_LIBRARY_PATH on Linux.

The only thing you might want to change is to run the tom application in the new terminal window. To do so, hit Ctrl+5 to open the Project Settings tab and select Run in the left sidebar to open the Run Settings, then in the Run section select the Run in terminal checkbox.

You can also set the Command line arguments in this Run section, eg. the migrate:status.

To execute the tom application press Ctrl + r.

The output will look very similar to this if you add more migrations.

Tom migrations - migrate:status command output

Happy migrating 🎉👌

Finish

As the last thing, you can check that all the file properties were correctly set by the rc compiler.

Find the tom.exe file and press Alt + Enter to open the file properties. To check the executable manifest you can use eg. the Resource Hacker.

tom.exe file properties detail
- +

Building: Migrations

Introduction

We will try to create a working migrations console application called as tom in the terminal with the CMake and in the QtCreator IDE with the qmake build systems.

The tom console application also expects the following folders structure, let's create them.

cd 
mkdir tom/tom
cd tom

TinyORM source tree contains the tom example application, you can inspire or look at the source code. Also, TinyORM unit tests use a tom migrations internally to create the database structure, internally called as the tom migrations for unit tests.

All these three console applications the tom example, tom migrations for unit tests, and the application described in this tutorial have practically identical source code (the main.cpp file).

note

The tom is able to generate DDL queries for all the supported databases databases.

info

You can see the Tom showcase image of how the resulting tom console application will look like.

Install dependencies

First, install the vcpkg package manager as is described here.

The range-v3 and tabulate libraries are required dependencies because TinyORM uses them in header files, you have to install them before you can use TinyORM. The tabulate library is only needed in the tom migrations it's used by the migrate:status command.

There are two ways how to install the range-v3 and tabulate libraries using vcpkg.

Also, don't forget to build the TinyORM library with the tom source code enabled (it's enabled by default) as is described here.

Using vcpkg.json (manifest mode)

Create a vcpkg.json file with the following content. CMake example below uses this method.

cd tom
vim vcpkg.json
vcpkg.json
{
"$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json",
"name": "tom",
"version-semver": "0.1.0",
"description": "Tom console application for TinyORM C++ library",
"homepage": "https://github.com/silverqx/TinyORM",
"documentation": "https://www.tinyorm.org/building/migrations",
"maintainers": "Silver Zachara <silver.zachara@gmail.com>",
"supports": "!(uwp | arm | android | emscripten | osx | ios | xbox | freebsd | openbsd | wasm32)",
"dependencies": [
"range-v3",
"tabulate"
]
}
note

Only CMake via the toolchain file supports this method.

Using vcpkg install (manually)

This method can be used with both CMake and qmake.

cd ../../vcpkg

vcpkg search range-v3
vcpkg search tabulate
vcpkg install range-v3 tabulate
vcpkg list

Source code

Let's start in the tom project folder.

cd /tom/tom

Main file

Create main.cpp source file.

vim main.cpp
tip

To paste a source code correctly in vim, press Shift + p.

And paste the following code.

main.cpp
#include <orm/db.hpp>

#include <tom/application.hpp>

#include "migrations/2014_10_12_000000_create_posts_table.hpp"

#include "seeders/databaseseeder.hpp"

using Orm::DatabaseManager;
using Orm::DB;

using TomApplication = Tom::Application;

using namespace Migrations; // NOLINT(google-build-using-namespace)
using namespace Seeders; // NOLINT(google-build-using-namespace)

/*! Create the database manager instance and add a database connection. */
std::shared_ptr<DatabaseManager> setupDatabaseManager();

/*! C++ main function. */
int main(int argc, char *argv[])
{
try {
// Ownership of the shared_ptr()
auto db = setupDatabaseManager();

return TomApplication(argc, argv, std::move(db), "TOM_EXAMPLE_ENV")
.migrations<CreatePostsTable>()
.seeders<DatabaseSeeder>()
// Fire it up 🔥🚀✨
.run();

} catch (const std::exception &e) {

TomApplication::logException(e);
}

return EXIT_FAILURE;
}

std::shared_ptr<DatabaseManager> setupDatabaseManager()
{
using namespace Orm::Constants; // NOLINT(google-build-using-namespace)

// Ownership of the shared_ptr()
return DB::create({
{driver_, QMYSQL},
{host_, qEnvironmentVariable("DB_MYSQL_HOST", H127001)},
{port_, qEnvironmentVariable("DB_MYSQL_PORT", P3306)},
{database_, qEnvironmentVariable("DB_MYSQL_DATABASE", EMPTY)},
{username_, qEnvironmentVariable("DB_MYSQL_USERNAME", EMPTY)},
{password_, qEnvironmentVariable("DB_MYSQL_PASSWORD", EMPTY)},
{charset_, qEnvironmentVariable("DB_MYSQL_CHARSET", UTF8MB4)},
{collation_, qEnvironmentVariable("DB_MYSQL_COLLATION", UTF8MB40900aici)},
{timezone_, TZ00},
/* Specifies what time zone all QDateTime-s will have, the overridden default is
the Qt::UTC, set to the Qt::LocalTime or QtTimeZoneType::DontConvert to use
the system local time. */
{qt_timezone, QVariant::fromValue(Qt::UTC)},
{strict_, true},
},
QStringLiteral("tinyorm_tom_mysql")); // shell:connection
}
tip

If you have defined more database connections then you can tag the lines with the database connection names with the // shell:connection comment and this connection names will be provided to the bash, zsh, pwsh completions for the --database= option 😎, example.

Migrations

If you have already built the tom application then you can generate a migrations using the make:migration command 😎.

tom make:migration create_posts_table

Below is the expected folders structure for the migrations. The migrations.pri file is used only by the qmake build system and is not needed with CMake builds.

tom/
└── database/
├── migrations/
├── seeders/
├── migrations.pri
└── seeders.pri

Let's create the first migration manually.

mkdir database/migrations

vim database/migrations/2014_10_12_000000_create_posts_table.hpp

And paste the following code.

database/migrations/2014_10_12_000000_create_posts_table.hpp
#pragma once

#include <tom/migration.hpp>

namespace Migrations
{

struct CreatePostsTable : Migration
{
/*! Filename of the migration file. */
T_MIGRATION

/*! Run the migrations. */
void up() const override
{
Schema::create("posts", [](Blueprint &table)
{
table.id();

table.string(NAME);
table.timestamps();
});
}

/*! Reverse the migrations. */
void down() const override
{
Schema::dropIfExists("posts");
}
};

} // namespace Migrations
tip

The TinyORM source tree contains the CreatePostsTable example migration that also acts as the full-fledged example migration. It has defined and also nicely commented all possible features that migration classes can use or define.

info

If you want, you can also build the tom application without the migrations, simply comment out the migrations method and the corresponding #include "migrations/xyz.hpp" files.

Seeders

If you have already built the tom application then you can generate a seeder using the make:seeder command 😎.

tom make:seeder PostSeeder

The expected folders structure is described a few paragraphs above. The seeders.pri file is used only by the qmake build system and is not needed with CMake builds.

Let's create the root seeder class manually.

mkdir database/seeders

vim database/seeders/databaseseeder.hpp

And paste the following code.

database/seeders/databaseseeder.hpp
#pragma once

#include <tom/seeder.hpp>

namespace Seeders
{

/*! Main database seeder. */
struct DatabaseSeeder : Seeder
{
/*! Run the database seeders. */
void run() override
{
DB::table("posts")->insert({
{{"name", "1. post"}},
{{"name", "2. post"}},
});
}
};

} // namespace Seeders
tip

The TinyORM source tree contains the DatabaseSeeder root seeder example class that also acts as the full-fledged example seeder. It has defined and also nicely commented all possible features that seeder classes can use or define.

tip

You can create more seeder classes like this and use the call<>() method to invoke them as is described in the Calling Additional Seeders section.

Migrations with CMake

Create a folder for the CMake build.

cd ..
mkdir tom-builds-cmake/build-debug

cd tom

CMake project

Create CMakeLists.txt file with the following content. I leave the comments in the CMakeLists.txt file because it's not as simple as the Hello world example; to make it clear what's going on.

CMakeLists.txt
cmake_minimum_required(VERSION VERSION 3.22...3.29 FATAL_ERROR)

# Specify the C++ standard
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# Initialize variables
# ---

set(Tom_ns tom)
set(Tom_target tom)

file(REAL_PATH "../../TinyORM" TinyMainDir)

set(TinyOrmSourceDir "${TinyMainDir}/TinyORM")
set(TinyOrmBuildDir "${TinyMainDir}/TinyORM-builds-cmake/build-debug")

# TinyORM CMake modules (needed to set the executable version and RC file on Windows)
list(APPEND CMAKE_MODULE_PATH "${TinyOrmSourceDir}/cmake/CommonModules")

# build tree
list(APPEND CMAKE_PREFIX_PATH "${TinyOrmBuildDir}")

# Initialize Project Version
# ---

include(TinyHelpers)
tiny_read_version(TINY_VERSION
TINY_VERSION_MAJOR TINY_VERSION_MINOR TINY_VERSION_PATCH TINY_VERSION_TWEAK
VERSION_HEADER "${TinyOrmSourceDir}/tom/include/tom/version.hpp"
PREFIX TINYTOM
HEADER_FOR "${Tom_ns}"
)

# Basic project
# ---

project(${Tom_ns}
DESCRIPTION "Tom console application for TinyORM C++ library"
HOMEPAGE_URL "https://www.tinyorm.org"
LANGUAGES CXX
VERSION ${TINY_VERSION}
)

# Tom command-line application
# ---

add_executable(${Tom_target}
main.cpp
)
add_executable(${Tom_ns}::${Tom_target} ALIAS ${Tom_target})

# Tom command-line application specific configuration
# ---

set_target_properties(${Tom_target}
PROPERTIES
C_VISIBILITY_PRESET "hidden"
CXX_VISIBILITY_PRESET "hidden"
VISIBILITY_INLINES_HIDDEN YES
VERSION ${PROJECT_VERSION}
)

target_include_directories(${Tom_target}
PRIVATE "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/database>"
)

# Tom command-line application defines
# ---

target_compile_definitions(${Tom_target}
PRIVATE
PROJECT_TOM
)

# Windows resource and manifest files
# ---

# Find icons, tom/version.hpp, and Windows manifest file for MinGW
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
tiny_set_rc_flags("-I \"${TinyOrmSourceDir}/tom/resources\"")
endif()

include(TinyResourceAndManifest)
tiny_resource_and_manifest(${Tom_target}
OUTPUT_DIR "${TINY_BUILD_GENDIR}/tmp/"
RESOURCES_DIR "${TinyOrmSourceDir}/tom/resources"
)

# Resolve and link dependencies
# ---

find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)
find_package(TinyOrm 0.37.1 CONFIG REQUIRED)

# Unconditional dependencies
target_link_libraries(${Tom_target}
PRIVATE
Qt${QT_VERSION_MAJOR}::Core
TinyOrm::TinyOrm
)

Build migrations

Now you are ready to configure tom CMake application. Don't forget to prepare the build environment with the qtenv6.ps1 command if you are building with the msvc.

cd ../tom-builds-cmake/build-debug
cmake.exe `
-S "/tom/tom" `
-B "/tom/tom-builds-cmake/build-debug" `
-G 'Ninja' `
-D CMAKE_BUILD_TYPE:STRING='Debug' `
-D CMAKE_TOOLCHAIN_FILE:FILEPATH="/vcpkg/scripts/buildsystems/vcpkg.cmake" `
-D CMAKE_INSTALL_PREFIX:PATH="/tmp/tom"

And build.

cmake --build . --target all

Execute migrations

Do not forget to add TinyOrm0d.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so tom application can find it during execution, as is described here.

$env:Path = "\TinyORM\TinyORM-builds-cmake\build-debug;" + $env:Path

Execute tom application.

.\tom.exe migrate:status

The output will look something like this.

Tom migrations - migrate:status command output

See also the final thoughts on how to verify the tom executable file properties.

Happy migrating 🎉👌

Migrations with qmake

Create a folder for the qmake build.

cd /tom

mkdir tom-builds-qmake

The source code is the same as for the Migrations with CMake console application.

qmake project

Create tom.pro qmake file with the following content.

cd tom
vim tom.pro
tip

To paste a source code correctly in vim, press Shift + p.

tom.pro
QT -= gui

TEMPLATE = app
TARGET = tom

CONFIG *= cmdline

DEFINES *= PROJECT_TOM

SOURCES += $$PWD/main.cpp

# Database migrations
include($$PWD/database/migrations.pri)
# Database seeders
include($$PWD/database/seeders.pri)

# Auto-configure TinyORM library for the migrations purposes 🔥
include($$TINY_MAIN_DIR/TinyORM/qmake/tom.pri)
caution

The exact folders structure is crucial in this example because the paths to the TinyORM source and build folders are relative.

caution

Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

Auto-configure using .qmake.conf and .env

If you want to have properly configured DEFINES (C preprocessor macros), have Qt headers marked as system headers, or eg. have properly set properties of an executable file such as version and description, then you need to specify a path to the TinyORM qmake features (.prf files) which handle this correctly; this path is provided by the QMAKEFEATURES variable and can only be set in the .qmake.conf file.

tip

Read the Consume TinyOrm library (qmake) section, as everything that is described in that section applies here as well.

Create the .qmake.conf file in the tom application root folder with the following content.

.qmake.conf
# Path to the PARENT folder of the TinyORM source folder
TINY_MAIN_DIR = $$clean_path($$PWD/../../TinyORM/)
# To find .env and .env.$$QMAKE_PLATFORM files
TINY_DOTENV_ROOT = $$PWD
# Path to the current build tree (used to guess the TinyORM build tree)
#TINY_BUILD_TREE = $$shadowed($$PWD)

# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants
QMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)

Then, create a .env.(win32|unix|mingw) file in the tom application root folder with the following content.

# Names and values of these qmake variables are crucial, they are used in the tom.pro
# Please pay special attention to letter casing in paths, especially TinyOrm vs TinyORM!

# Path to the TinyORM build folder
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug/)

# Path to the vcpkg - range-v3 and tabulate
# Will use the TINY_VCPKG_ROOT or VCPKG_ROOT environment variable if is empty
TINY_VCPKG_ROOT = $$clean_path($$PWD/../../../vcpkg/)
TINY_VCPKG_TRIPLET = x64-windows

# Enable ccache wrapper
#CONFIG *= tiny_ccache_win32

Don't forget to update the TINYORM_BUILD_TREE and TINY_VCPKG_ROOT folder paths to your needs if you are not using the recommended Folders structure.

You can use the Partial guessing of the TINYORM_BUILD_TREE if you don't like to specify it manually. Just comment out the TINYORM_BUILD_TREE and uncomment the TINY_BUILD_TREE = $$shadowed($$PWD) in the .qmake.conf file.

tip

You can entirely avoid the .env files, just move the TINYORM_BUILD_TREE to the .qmake.conf or remove it by help of Partial guessing of the TINYORM_BUILD_TREE and set the VCPKG_ROOT environment variable at system level as is described in Set up vcpkg environment.

info

Configuring by the .qmake.conf and .env files has one big advantage, which is that you don't have to modify the project files.

Migrations source files

Create database/migrations.pri file and paste the following code.

database/migrations.pri
INCLUDEPATH *= $$PWD

HEADERS += \
$$PWD/migrations/2014_10_12_000000_create_posts_table.hpp \

Seeders source files

Create database/seeders.pri file and paste the following code.

database/seeders.pri
INCLUDEPATH *= $$PWD

HEADERS += \
$$PWD/seeders/databaseseeder.hpp \

Build migrations

tip

I recommend creating a new Session in the QtCreator IDE as is described here.

Now you can open the tom.pro project in the QtCreator IDE.

This will open the Configure Project tab, select some kit and update build folder paths to meet our folders structure or like you want.

tom - QtCreator - Configure Project
tip

You can force the QtCreator to generate a build folders structure as is described here.

You are ready to configure build options, hit Ctrl+5 to open Project Settings tab and select Build in the left sidebar to open the Build Settings, it should look similar to the following picture.

tom - QtCreator - Build Settings

Disable QML debugging and profiling and Qt Quick Compiler, they are not used.

In the left sidebar open Dependencies and check TinyORM project and Synchronize configuration, this setting ensures that the current project will be rebuilt correctly when the TinyORM library source code changes.

Everything is ready to build, you can press Ctrl+b to build the project.

Execute migrations

The QtCreator takes care of all the necessary configurations, sets up the build environment correctly, and also prepends dependency libraries on the system path on Windows and on the LD_LIBRARY_PATH on Linux.

The only thing you might want to change is to run the tom application in the new terminal window. To do so, hit Ctrl+5 to open the Project Settings tab and select Run in the left sidebar to open the Run Settings, then in the Run section select the Run in terminal checkbox.

You can also set the Command line arguments in this Run section, eg. the migrate:status.

To execute the tom application press Ctrl + r.

The output will look very similar to this if you add more migrations.

Tom migrations - migrate:status command output

Happy migrating 🎉👌

Finish

As the last thing, you can check that all the file properties were correctly set by the rc compiler.

Find the tom.exe file and press Alt + Enter to open the file properties. To check the executable manifest you can use eg. the Resource Hacker.

tom.exe file properties detail
+ \ No newline at end of file diff --git a/building/tinyorm.html b/building/tinyorm.html index 4320a55a8..93f8447c5 100644 --- a/building/tinyorm.html +++ b/building/tinyorm.html @@ -14,7 +14,7 @@ - + @@ -22,8 +22,8 @@

Building: TinyORM

Introduction

The build systems supported out of the box are CMake and qmake.

info

All examples below assume that pwsh runs on Windows and bash runs on Linux.

Common Prerequisites

Install the required dependencies before starting.

caution

The QSqlDatabase depends on QCoreApplication from Qt v6.5.3 so you must create the QCoreApplication instance before you will call anything from the TinyORM library. 🫤 The change was made here.

Windows Prerequisites

Build environment scripts

The Visual Studio does not provide vcvars scripts for pwsh, you can use vcvars64.ps1 provided by TinyORM in the tools/ folder. Place them on the $env:Path user/system path and they will be available system-wide.

The same is true for the Qt Framework, it doesn't provide qtenv scripts for pwsh too. You can create your own script, place it on the $env:Path user/system path and it will be available system-wide.

Here is one simple example for pwsh.

Write-Host 'Setting up environment for Qt 6.7.0 usage...' -ForegroundColor Magenta
$env:Path = 'C:\Qt\6.7.0\msvc2019_64\bin;' + $env:Path
. E:\dotfiles\bin\vcvars64.ps1

And here for Linux.

echo 'Setting up environment for Qt 6.7.0 usage...'

export PATH=/opt/Qt/6.7.0/gcc_64/bin${PATH:+:}$PATH
export LD_LIBRARY_PATH=/opt/Qt/6.7.0/gcc_64/lib${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH

Open Local Security Policy, go to Local Policies - User Rights Assignment, open Create symbolic links and add your user account or user group, restart when it doesn't apply immediately.

Folders structure

All tinyorm.org examples are based on the following folders structure. The tom folder will contain a migrations console application.

tip

You can set the root and application folder paths in the form below and they will be used across the whole www.tinyorm.org website. 🥳 The pwsh shell is supposed to use on Windows and the bash shell on Linux, but it is not a requirement.

Current pwsh path 



├──
│ ├── HelloWorld/
│ | ├── HelloWorld/
│ | ├── HelloWorld-builds-cmake/
│ | | └── build-debug/
│ | └── HelloWorld-builds-qmake/
│ | └── build-debug/
│ ├── TinyORM/
│ | ├── TinyORM/
│ | ├── TinyORM-builds-cmake/
│ | │ ├── build-gcc-debug/
│ | │ ├── build-gcc-release/
│ | │ └── build-clang-debug/
│ | └── TinyORM-builds-qmake/
│ | ├── build-debug/
│ | ├── build-TinyORM-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug/
│ | └── build-TinyORM-Desktop_Qt_5_15_2_MSYS2_UCRT64_64bit-Release/
│ └── tom/
│ ├── tom/
│ │ └── database/
│ │ ├── migrations/
│ │ ├── seeders/
│ │ ├── migrations.pri
│ │ └── seeders.pri
│ ├── tom-builds-cmake/
│ │ └── build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/
│ └── tom-builds-qmake/
│ ├── build-TinyORM-Desktop_Qt_5_15_3_MSYS2_UCRT64_64bit-Release/
│ └── build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/
├── tmp/
└── vcpkg/
danger

Avoid paths with spaces with the qmake build system, it will not compile.

tip

You can force the QtCreator to generate a build folders structure as is described above.

To generate the required folders structure set the Settings - Build & Run - Default Build Properties - Default build directory to:
-../%{Project:Name}-builds-%{BuildSystem:Name}/%{JS: Util.asciify("build-%{Project:Name}-%{Kit:FileSystemName}-%{BuildConfig:Name}")}

Getting started

Prepare compilation environment, we need to put the Qt Framework and Visual Studio MSVC compiler on the path on Windows. The compiler is already on the path on Linux and you can export PATH and LD_LIBRARY_PATH for Qt Framework, or use our qtenvX scripts described above.

mkdir 
cd
$env:Path = 'C:\Qt\6.7.0\msvc2019_64\bin;' + $env:Path
vcvars64.ps1
tip

You can also use the tools/Add-FolderOnPath.ps1 pwsh script to fastly prepend a path or pwd on the system PATH.

vcpkg

Installing the vcpkg is highly recommended, it simplifies installation of the range-v3 and tabulate dependencies.

git clone git@github.com:microsoft/vcpkg.git
cd vcpkg
.\bootstrap-vcpkg.bat

Add vcpkg on the system path, add the following to the .bashrc or .zshrc on Linux.

export PATH=/vcpkg${PATH:+:}$PATH

On Windows, open the Environment variables dialog and add vcpkg on the user PATH.

Or you can export it for the current session only.

$env:Path = "\vcpkg;" + $env:Path

Set up vcpkg environment

To export vcpkg environment variables globally, add it to the .bashrc or .zshrc on Linux, and you can use the Environment variables dialog on Windows.

Linux
export VCPKG_DEFAULT_TRIPLET=x64-linux
#export VCPKG_DEFAULT_HOST_TRIPLET=x64-linux
export VCPKG_MAX_CONCURRENCY=11
export VCPKG_OVERLAY_PORTS="$HOME/.local/share/vcpkg/ports"
export VCPKG_OVERLAY_TRIPLETS="$HOME/.local/share/vcpkg/triplets"
export VCPKG_ROOT="$HOME/Code/c/vcpkg"
info

It is recommended to define these variables globally because the CMake and qmake build system are able to detect the vcpkg installation from them so you don't have to configure them manually to detect the vcpkg installation.

tip

On Windows, it's always better to create these types of variables as user variables instead of system variables in the Environment variables dialog.

C preprocessor macros

The following table summarizes all the C preprocessor macros defined in the TinyORM library. These C macros are configured by CMake or qmake build systems. They are not sorted alphabetically, but they are sorted by how significant they are.

In the CMake build system, all the C macros are auto-detected / auto-configured or controlled by CMake build options, so you don't have to care too much about them.

In the qmake build is important whether you are building TinyORM library or you are building your application and linking against TinyORM library. When you are building the TinyORM library, all the C macros are auto-detected / auto-configured or controlled by qmake build options, so you don't have to care too much about them.

But a special situation is when you are building your application / library and you are linking against TinyORM library. In this particular case, you must configure all these C macros manually! For this reason, the TinyOrm.pri has been created, so that's not a big deal either. Little more info here.

C Macro NameDescription
TINYORM_LINKING_SHAREDMust be defined when you are linking against TinyORM shared build (dll library), exported classes and functions will be tagged with __declspec(dllimport) on msvc and visibility("default") on GCC >= 4.
TINYORM_BUILDING_SHAREDDefined when TinyORM is built as a dll library (shared build).
TINYORM_DEBUGDefined in the debug build.
TINYORM_NO_DEBUGDefined in the release build.
TINYORM_DEBUG_SQLDefined in the debug build.
TINYORM_NO_DEBUG_SQLDefined in the release build.
TINYORM_MYSQL_PINGEnable Orm::MySqlConnection::pingDatabase() method.
Defined when mysql_ping (qmake) / MYSQL_PING (cmake) configuration build option is enabled.
TINYORM_DISABLE_ORMControls the compilation of all ORM-related source code, when this macro is defined, then only the query builder without ORM is compiled. Also excludes ORM-related unit tests.
Defined when disable_orm (qmake) / ORM (cmake) configuration build option is enabled (qmake) / disabled (cmake).
TINYORM_EXTERN_CONSTANTSDefined when extern constants are used. Extern constants are enabled by default for shared builds and disabled for static builds.
Described at qmake / CMake how it works.
TINYORM_INLINE_CONSTANTSDefined when global inline constants are used.
Defined when inline_constants (qmake) / INLINE_CONSTANTS (cmake) configuration build option is enabled.
TINYORM_TESTS_CODEEnable code needed by unit tests, eg. connection overriding in the Orm::Tiny::Model.
Defined when build_tests (qmake) / BUILD_TESTS (cmake) configuration build option is enabled.
TINYORM_DISABLE_THREAD_LOCALRemove all thread_local storage duration specifiers, it disables multi-threading support.
Defined when disable_thread_local (qmake) / DISABLE_THREAD_LOCAL (cmake) configuration build option is enabled.
TINYTOM_MIGRATIONS_DIRDefault migrations path for the make:migration command, can be an absolute or relative path (to the pwd).
Default value: database/migrations (relative to the pwd)
Defined by TOM_MIGRATIONS_DIR (cmake) configuration build option.
(qmake note) You can use DEFINES += TINYTOM_MIGRATIONS_DIR="\"database/migrations\"" on the command-line or set it in the main conf.pri file.
TINYTOM_MODELS_DIRDefault models path for the make:model command, can be an absolute or relative path (to the pwd).
Default value: database/models (relative to the pwd)
Defined by TOM_MODELS_DIR (cmake) configuration build option.
(qmake note) You can use DEFINES += TINYTOM_MODELS_DIR="\"database/models\"" on the command-line or set it in the main conf.pri file.
TINYTOM_SEEDERS_DIRDefault seeders path for the make:seeder command, can be an absolute or relative path (to the pwd).
Default value: database/seeders (relative to the pwd)
Defined by TOM_SEEDERS_DIR (cmake) configuration build option.
(qmake note) You can use DEFINES += TINYTOM_SEEDERS_DIR="\"database/seeders\"" on the command-line or set it in the main conf.pri file.
TINYORM_USING_PCHDefined if building with precompiled headers.
Controlled by qmake / CMake.

Building with CMake

tip

If something is not clear, you can still look at GitHub Action workflows how a building is done.

First, create a basic folder structure and then clone the TinyORM project.

cd 
mkdir /TinyORM/TinyORM-builds-cmake/build-debug

cd /TinyORM
git clone git@github.com:silverqx/TinyORM.git

Configure & Build (cmake)

Now you are ready to configure the TinyORM library.

cd TinyORM-builds-cmake/build-debug
cmake.exe `
-S "/TinyORM/TinyORM" `
-B "/TinyORM/TinyORM-builds-cmake/build-debug" `
-G 'Ninja' `
-D CMAKE_BUILD_TYPE:STRING='Debug' `
-D CMAKE_TOOLCHAIN_FILE:FILEPATH="/vcpkg/scripts/buildsystems/vcpkg.cmake" `
-D CMAKE_INSTALL_PREFIX:PATH="/tmp/TinyORM" `
-D BUILD_TESTS:BOOL=OFF `
-D MATCH_EQUAL_EXPORTED_BUILDTREE:BOOL=ON `
-D MYSQL_PING:BOOL=OFF `
-D TOM:BOOL=ON `
-D TOM_EXAMPLE:BOOL=OFF `
-D VERBOSE_CONFIGURE:BOOL=ON
CMake STRICT_MODE option

The STRICT_MODE CMake configuration option was added in TinyORM v0.37.0. This option was added to avoid the propagation of aggressive strict warning compiler/linker options and Qt definitions from the TinyORM library to user code through the TinyOrm::CommonConfig interface library.

TinyORM uses the strictest warning level options, virtually anything that can be enabled is enabled to produce a better code. I highly recommend enabling this option to produce better code and to follow good practices. It also helps to follow the ISOCPP C++ Core Guidelines standards.

If you want to enable these strict warning options in your code, you can enable the STRICT_MODE CMake configuration option and they will be propagated to your code. You can also enabled it globally using the TINYORM_STRICT_MODE environment variable, and the value of this environment variable will be picked up during initial CMake configuration as the default value for the STRICT_MODE CMake configuration option.

You can achieve the same result by manually linking against the TinyOrm::CommonConfig interface library when the STRICT_MODE is set to OFF.

target_link_libraries(<target> PRIVATE TinyOrm::CommonConfig)
info

The recommended way is to set the TINYORM_STRICT_MODE environment variable to 1 or ON.

Build TinyORM

And build. You don't have to install it, you can use the build tree directly if you want.

cmake --build . --target all
cmake --install .

Or build and install in one step.

cmake --build . --target install
info

CMake multi-config generators like Ninja Multi-Config or Visual Studio 16 2019 are also supported.

CMake build options

Option NameDefaultDescription
BUILD_DRIVERSOFFBuild TinyDrivers SQL database drivers (core/common code; replaces QtSql module).
BUILD_MYSQL_DRIVERSOFFBuild TinyDrivers MySQL database driver.
Available when: BUILD_DRIVERS
BUILD_SHARED_LIBSONBuild as a shared/static library.
BUILD_TESTSOFFBuild TinyORM unit tests.
BUILD_TREE_DEPLOYONCopy TinyDrivers and TinyMySql libraries to the root of the build tree.
DRIVERS_TYPESharedHow to build and link against TinyDrivers SQL database drivers.
The Static value will be select by default when the BUILD_SHARED_LIBS is OFF.
Supported values: Shared, Loadable, and Static
Available when: BUILD_DRIVERS AND BUILD_SHARED_LIBS
INLINE_CONSTANTSOFFUse inline constants instead of extern constants in the shared build.
OFF is highly recommended for the shared build;
is always ON for the static build.
Available when: BUILD_SHARED_LIBS
MSVC_RUNTIME_DYNAMICONUse MSVC dynamic runtime library (-MD) instead of static (-MT), also considers a Debug configuration (-MTd, -MDd).
Available when: MSVC AND NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY
MYSQL_PINGOFFEnable Orm::MySqlConnection::pingDatabase() method.
ORMONControls the compilation of all ORM-related source code, when this option is disabled, then only the query builder without ORM is compiled. Also excludes ORM-related unit tests.
STRICT_MODEOFFControls propagation of strict compiler/linker options and Qt definitions using the TinyOrm::CommonConfig interface library to the user code.
(highly recommended; can also be set with the TINYORM_STRICT_MODE environment variable; described here).
TOMONControls the compilation of all Tom-related source code, when this option is disabled, then it also excludes Tom-related unit tests.
TOM_EXAMPLEOFFBuild the tom console application example.
TOM_MIGRATIONS_DIR-Default migrations path for the make:migration command, can be an absolute or relative path (to the pwd).
Default value: database/migrations (relative to the pwd)
TOM_MODELS_DIR-Default models path for the make:model command, can be an absolute or relative path (to the pwd).
Default value: database/models (relative to the pwd)
TOM_SEEDERS_DIR-Default seeders path for the make:seeder command, can be an absolute or relative path (to the pwd).
Default value: database/seeders (relative to the pwd)
VERBOSE_CONFIGUREOFFShow information about PACKAGES_FOUND / PACKAGES_NOT_FOUND in the CMake configure output.

Advanced TinyORM options.

Option NameDefaultDescription
DISABLE_THREAD_LOCALOFFRemove all thread_local storage duration specifiers, it disables multi-threading support.
MATCH_EQUAL_EXPORTED_BUILDTREEOFFExported package configuration from the build tree is considered to match only when the build type of application/library that is linking against the TinyORM library is equal.
Available when:
CMAKE_EXPORT_PACKAGE_REGISTRY AND NOT TINY_IS_MULTI_CONFIG

Important CMake options.

Option NameDefaultDescription
CMAKE_DISABLE_PRECOMPILE_HEADERSOFFDisable precompiled headers.
CMAKE_CXX_COMPILERautoThe full path to the C++ compiler.
CMAKE_CXX_COMPILER_LAUNCHER-Default compiler launcher to use for the C++ compiler.
Can be used to enable ccache, eg. ccache.exe on MinGW or /usr/bin/ccache on Linux.
CMAKE_EXPORT_PACKAGE_REGISTRYONEnable the export(TinyOrm) command.
TinyORM sets this variable to ON by default.
CMAKE_VERBOSE_MAKEFILEOFFEnable verbose output from Makefile builds.

Consume TinyOrm library (cmake)

In your application or library CMakeLists.txt file add following find_package() call.

CMakeLists.txt
find_package(TinyOrm 0.37.0 CONFIG REQUIRED)

If the TinyORM build tree is not exported to the CMake's User Package Registry then also add the TinyORM build tree or CMAKE_INSTALL_PREFIX folder to the CMAKE_PREFIX_PATH, so CMake can find TinyORM's package configuration file during find_package(TinyOrm) call.

# build tree
list(APPEND CMAKE_PREFIX_PATH "/TinyORM/TinyORM-builds-cmake/build-debug")

# installation folder - CMAKE_INSTALL_PREFIX
list(APPEND CMAKE_PREFIX_PATH "/tmp/TinyORM")

Or as an alternative, you can set CMAKE_PREFIX_PATH environment variable.

As the last thing, do not forget to add TinyOrm0d.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so your application can find it during execution.

$env:Path = "\TinyORM\TinyORM-builds-cmake\build-debug;" + $env:Path

Now you can try the HelloWorld CMake example.

info

You can also try the FetchContent method to fastly link against the TinyORM library.

Building with qmake

First, create a basic folder structure and then clone the TinyORM project.

cd 
mkdir /TinyORM/TinyORM-builds-qmake

cd /TinyORM
git clone git@github.com:silverqx/TinyORM.git

Install dependencies

With the qmake build system, you have to install TinyORM dependencies manually. We will use the vcpkg package manager.

cd ../../vcpkg

vcpkg search range-v3
vcpkg search tabulate
vcpkg install range-v3 tabulate
vcpkg list

On Linux, you can install the range-v3 library and some other dependencies with the package manager.

Configure & Build (qmake)

Open QtCreator IDE

tip

I recommend creating a new Session in the QtCreator, this way you will have all the examples in one place and as a bonus, everything will be in the same place when you close and reopen QtCreator IDE. You can name it tinyorm.org or TinyORM examples, it is up to you.

tip

If you are using sessions, you can use a single clangd instance for all projects in this session in the QtCreator IDE. One significant advantage of this method is that the .qtc_clangd/ folder will not be created in the build folder, but will be stored globally in the Roaming profile. You can enable it in the Settings - C++ - Clangd - Sessions with a single clangd instance.

Configure TinyORM

Now you are ready to configure the TinyORM library. There are two ways how to configure the TinyORM library and it's the new Auto-configure feature added in TinyORM v0.34.0 using the .env files and the old way using the conf.pri files.

Auto-configuration and tiny_dotenv

This is the new recommended method to auto-configure TinyORM's qmake build system and also the dependencies, it was added in TinyORM v0.34.0. You need to copy the prepared .env.(win32|unix|mingw).example file to the .env.(win32|unix|mingw). One .env example file is prepared for each supported platform.

All prepared .env.(win32|unix|mingw).example files are simple and clear. You can also create a common .env file that is included before the platform-specific .env.(win32|unix|mingw) files.

cd /TinyORM/TinyORM

cp .env.win32.example .env.win32

And that is all, if you have correctly set all qmake variables in this .env.(win32|unix|mingw) file or you have correctly set environment variables, then the qmake build system should be able to auto-detect all dependencies . 🔥

info

The Auto-configuration and Environment files internals are described at the end to make this section more clear.

tip

The Auto-configuration feature can be turned off using the disable_autoconf qmake configuration option (eg. CONFIG*=disable_autoconf).

tip

The tiny_dotenv feature can be turned off using the disable_dotenv qmake configuration option (eg. CONFIG*=disable_dotenv).

Manual configuration (conf.pri)

This is the old method used before TinyORM v0.34.0. You need to copy the conf.pri.example files to conf.pri (there are four, one for every project or sub-project) and manually update the INCLUDEPATH and LIBS to configure TinyORM's qmake build dependencies. This way you can override any qmake build options or variables.

To disable the Auto-configuration feature you must define the disable_autoconf qmake configuration option (eg. CONFIG*=disable_autoconf) because from TinyORM v0.34.0 is the Auto-configuration feature enabled by default.

You can also remove all .env files or turn off the tiny_dotenv feature using CONFIG*=disable_dotenv. You can use them all at once if you want, .env and also conf.pri files.

conf.pri files are nicely commented on, so you can see what needs to be modified.

cd /TinyORM/TinyORM

cp conf.pri.example conf.pri
cp tests/conf.pri.example tests/conf.pri
cp tests/testdata_tom/conf.pri.example tests/testdata_tom/conf.pri
cp examples/tom/conf.pri.example examples/tom/conf.pri
info

The Manual configuration internals are described at the end to make this section more clear.

note

The Manual configuration is still relevant if you have any non-standard installation of the vcpkg or MySQL and the Auto-configuration feature fails.

Opening TinyORM.pro (main project file)

Now you can open the TinyORM.pro project in the QtCreator IDE.

This will open the Configure Project tab, select some kit and update build folder paths to meet our folders structure or like you want.

TinyORM - QtCreator - Configure Project
tip

You can force the QtCreator to generate a build folders structure as is described above.

You are ready to configure build options, hit Ctrl+5 to open Project Settings tab and select Build in the left sidebar to open the Build Settings, it should look similar to the following picture.

Disable QML debugging and profiling and Qt Quick Compiler, they are not used.

TinyORM - QtCreator - Build Settings

If you want to change some TinyORM build options, you can pass them to the Build Steps - qmake TinyORM.pro - Additional arguments input field. It can look like this.

TinyORM - QtCreator - Build Settings - Additional arguments

Build TinyORM

Everything is ready for build, you can press Ctrl+b to build the project.

qmake build options

CONFIG Option NameDefaultDescription
build_loadable_driversOFFBuild TinyDrivers as a shared library and SQL database drivers (eg. TinyMySql) as shared libraries (Loadable modules) that are loaded at runtime using LoadLibrary() on Windows or dlopen() on Linux.
build_mysql_driverOFFBuild TinyDrivers MySQL database driver.
It's enabled by default when build_shared_drivers, build_loadable_drivers, or build_static_drivers is enabled.
Available when: build_shared_drivers OR build_loadable_drivers OR build_static_drivers
build_shared_driversOFFBuild TinyDrivers as a Shared library.
build_static_driversOFFBuild TinyDrivers as a Static library archive.
The build_static_drivers qmake configuration option will be select by default when the CONFIG*=staticlib is enabled.
build_testsOFFBuild TinyORM unit tests.
disable_autoconfOFFDisable the Auto-configuration feature (auto-configuration is enabled by default from TinyORM v0.34.0).
disable_dotenvOFFDisable the tiny_dotenv feature (environment files are enabled by default from TinyORM v0.34.0).
disable_thread_localOFFRemove all thread_local storage duration specifiers, it disables multi-threading support.
disable_ormOFFControls the compilation of all ORM-related source code, when this option is enabled, then only the query builder without ORM is compiled. Also excludes ORM-related unit tests.
disable_tomOFFControls the compilation of all Tom-related source code, when this option is disabled, then it also excludes Tom-related unit tests.
extern_constantsONUse extern constants instead of inline constants in the shared build.
ON is highly recommended for the shared build (by default);
is always OFF for the static build.
Available when: CONFIG(shared|dll):!inline_constants
inline_constantsOFFUse inline constants instead of extern constants in the shared build.
OFF is highly recommended for the shared build;
is always ON for the static build.
mysql_pingOFFEnable Orm::MySqlConnection::pingDatabase() method.
tiny_ccache_win32ONEnable compiler cache. Homepage
It works only on Windows systems. It works well with the MSYS2 g++, clang++, msvc, and clang-cl with msvc. It disables precompile_header as they are not supported on Windows and changes the -Zi compiler option to the -Z7 for debug builds as the -Zi compiler option is not supported (link to the issue).
tom_exampleOFFBuild the tom console application example.

Advanced TinyORM options.

Option NameDefaultDescription
ubsanOFFAllows to enable UBSan sanitizer (Clang only).

Important qmake options.

CONFIG Option NameDefaultDescription
ccacheOFFEnable compiler cache. Homepage
It works only on the Unix systems. It works well with the g++ and clang++ and also supports precompiled headers.
precompile_header-Enable precompiled headers, you can disable them with:
CONFIG-=precompile_header.
The precompile_header is enabled by default on msvc, g++, clang++, clang-cl on Windows and disabled by default on linux.
static
staticlib
OFFBuild as a static library (lib only).
If you want to build all libraries in the TinyORM project as static library archives and link against static libraries use the CONFIG += static. Don't use the CONFIG += staticlib.
See NOTES.txt for more information (search static vs staticlib).
static_runtimeOFFLink against the shared (dynamic) or static run-time library.
The -MD becomes -MT and -MDd becomes -MTd. It works only on MSVC and MinGW or MSYS2.
Please don't use this option.
Available when: msvc or mingw

Consume TinyOrm library (qmake)

The TinyOrm.pri file is available to simplify the integration of the TinyORM library into your application. It sets up and configures the CONFIG and DEFINES qmake variables, adds the TinyORM, tom, and vcpkg header files on the system INCLUDEPATH (cross-platform using the -isystem or -imsvc), links against the TinyORM shared or static library using the LIBS.

You can use it to configure the TinyORM library when you are linking against it. It does a very similar thing like the CMake's Find Modules feature.

Requirements

It has a few requirements, you need to:

  • specify path to the TinyORM qmake features (.prf files) using the QMAKEFEATURES variable that can only be set in the .qmake.conf file
  • specify qmake or environment variables to find the vcpkg installation (TINY_VCPKG_ROOT and TINY_VCPKG_TRIPLET)
  • specify path to the TinyORM build folder (TINYORM_BUILD_TREE)
  • build your application with the same CONFIG qmake variables that were used when building the TinyORM library

Let's explain one by one.

QMAKEFEATURES

Create the .qmake.conf file in your application root folder with the following content.

.qmake.conf
# Path to the PARENT folder of the TinyORM source folder
TINY_MAIN_DIR = $$clean_path(<your_path>)
# To find .env and .env.$$QMAKE_PLATFORM files in YOUR project
TINY_DOTENV_ROOT = $$PWD

# Path to the TinyORM build folder (specified manually)
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/)
# vcpkg - range-v3 and tabulate
TINY_VCPKG_ROOT = $$quote(<your_path>/vcpkg/)
#TINY_VCPKG_TRIPLET = x64-windows

# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants
QMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)

You can move all qmake variables that are part of the qmake configuration process to the .env file if you want (recommended), this is possible because the TinyOrm.pri enables the Environment files feature by default.

You can look at the Auto-configure using .qmake.conf and .env example for Hello world project of what must stay in the qmake.conf file and what can be moved to the .env files.

tip

You can use the Partial guessing of the TINYORM_BUILD_TREE if you don't like to specify it manually.

Variables affecting TinyOrm.pri

You must define the following variables before the TinyOrm.pri is included:

Variable NameDescription
TINYORM_BUILD_TREEPath to the TinyORM build folder.
TINY_VCPKG_ROOTPath to the vcpkg installation folder.
If not defined, then it tries to use the VCPKG_ROOT environment variable.
TINY_VCPKG_TRIPLETThe vcpkg triplet to use (vcpkg/installed/$$TINY_VCPKG_TRIPLET/).
If not defined, then it tries to guess the vcpkg triplet based on the current compiler and OS (based on the QMAKESPEC), and as the last thing, it tries to use the VCPKG_DEFAULT_TRIPLET environment variable.

These variables will be set after the configuration is done:

Variable NameDescription
TINY_BUILD_SUBFOLDERFolder by release type if CONFIG+=debug_and_release is defined (/debug, /release, or an empty string).
TINY_CCACHE_BUILDTo correctly link ccache build against a ccache build (_ccache or an empty string).
TINY_MSVC_VERSIONThe msvc compiler string (MSVC2022 or MSVC2019).
TINY_QT_VERSION_UNDERSCOREDUnderscored Qt version (eg. 6_7_0).
TINY_RELEASE_TYPE_CAMELBuild type string (Debug, Profile, or Release).
TINY_VCPKG_INCLUDEPath to the vcpkg include folder (vcpkg/installed/<triplet>/include/).

Then you simply include the TinyOrm.pri in your project file.

AnyProject.pro
include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)

And that is all, now you should be able to link against the TinyORM library. 👌

Manual configuration examples

Frankly, there is no reason to use the Manual configuration (define the variables described below before the TinyOrm.pri inclusion), the only reason to use it is when you want more control over this process or want to define everything yourself. I'll leave this section here to show how things work.

You will have to link against the TinyORM library manually if you don't set the TINYORM_BUILD_TREE qmake variable before the inclusion of the TinyOrm.pri file. The INCLUDEPATH is auto-detected every time.

# Link against TinyORM library
# ---
TINY_MAIN_DIR = $$clean_path(<your_path>)

# Configure TinyORM library
include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)

# TinyORM library path
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake)
LIBS += $$quote(-L$$TINYORM_BUILD_TREE/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/src$${TINY_BUILD_SUBFOLDER}/)
LIBS += -lTinyOrm

The same is true for the vcpkg include path. If you don't set the TINY_VCPKG_ROOT or have not defined the VCPKG_ROOT environment variable, then you need to set up the INCLUDEPATH for the vcpkg that provides the range-v3 and tabulate header files.

# vcpkg - range-v3 and tabulate
# ---
INCLUDEPATH += $$quote(<your_path>/vcpkg/installed/x64-windows/include/)

You can also use TinyORM's qmake function tiny_add_system_includepath() which handles INCLUDEPATH in a cross-platform way.

# vcpkg - range-v3 and tabulate
# ---
load(tiny_system_includepath)
tiny_add_system_includepath(<your_path>/vcpkg/installed/x64-linux/include/)

Do not forget to add TinyOrm0.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so your application can find it during execution.

$env:Path = "\TinyORM\TinyORM-builds-qmake\build-debug;" + $env:Path
tip

On Linux -isystem marks the directory as a system directory, it prevents warnings.

On Windows you can use QMAKE_CXXFLAGS_WARN_ON = -external:anglebrackets -external:W0, it applies a warning level 0 to the angel bracket includes; #include <file>.

With the clang-cl with MSVC you can use -imsvc.

Auto-configuration internals

The qmake build system does not support auto-configuration of dependencies out of the box but TinyORM from v0.34.0 added its own Auto-configuration feature along with the tiny_dotenv qmake feature. These new features allow us to auto-configure TinyORM project, and with their help, the conf.pri files can be skipped entirely.

While it adds additional complexity to the qmake configuration process, the benefits are significant.

The Auto-configuration feature is designed to find the vcpkg and MySQL installations, and tiny_dotenv to include the .env and .env.(win32|unix|mingw) files in the project's root folder. These new features can be configured using qmake and environment variables, and they also contain some guessing logic if these variables are not defined.

The Auto-configuration feature can be turned off using the disable_autoconf qmake configuration option (eg. CONFIG*=disable_autoconf).

These are qmake and environment variables that affect the Auto-configuration feature:

Variable NameDescription
TINY_VCPKG_ROOTPath to the vcpkg installation folder.
If not defined, then it tries to use the VCPKG_ROOT environment variable.
TINY_VCPKG_TRIPLETThe vcpkg triplet to use (vcpkg/installed/$$TINY_VCPKG_TRIPLET/).
If not defined, then it tries to guess the vcpkg triplet based on the current compiler and OS (based on the QMAKESPEC), and as the last thing, it tries to use the VCPKG_DEFAULT_TRIPLET environment variable.
TINY_MYSQL_ROOTPath to the MySQL installation folder.
If not defined, then it tries to guess the MySQL installation folder (win32 only): $$(ProgramFiles)/MySQL/MySQL Server (8.3|8.2|8.1|8.0|5.7)/

You can set these variables in the .env (recommended) or conf.pri files, in the .qmake.conf file (or wherever you want), or as environment variables.

These variables will be set after auto-configuration is done:

Variable NameDescription
TINY_VCPKG_INCLUDEPath to the vcpkg include folder (vcpkg/installed/<triplet>/include/).
TINY_MYSQL_INCLUDEPath to the MySQL include folder (MySQL Server 8.3/include/).
TINY_MYSQL_LIBPath to the MySQL lib folder (MySQL Server 8.3/lib/).

The TINY_MYSQL_INCLUDE and TINY_MYSQL_LIB are only set on win32 platform except mingw.

Environment files

The tiny_dotenv feature allows us to define the .env and .env.$$TINY_DOTENV_PLATFORM files in the project's root folder. These files are loaded as early as possible so you can affect the qmake configuration process. On the other hand, the conf.pri files are loaded as late as possible, and they can be used to override the qmake configuration.

The .env file is included first and is included on all platforms.

There is only one requirement for this feature to work correctly, and that is to set the TINY_DOTENV_ROOT qmake variable to the project's root folder. This variable is already set in the .qmake.conf file for the TinyORM project.

Then the following names are taken into account: .env, .env.win32, .env.unix, .env.mingw

.qmake.conf
# To find .env and .env.$$QMAKE_PLATFORM files
TINY_DOTENV_ROOT = $$PWD

The tiny_dotenv feature can be turned off using the disable_dotenv qmake configuration option (eg. CONFIG*=disable_dotenv).

caution

Environment files don't work in the CMake builds.

Partial guessing of the TINYORM_BUILD_TREE

You don't have to manually define the TINYORM_BUILD_TREE in .env or .qmake.conf files. The TINYORM_BUILD_TREE absolute path can be put together for you (this is happening inside the variables.pri file) and TinyORM build folder name can be guessed for you too.

You must define the following variables before the TinyOrm.pri will be included to make this real (set them in the .qmake.conf):

Variable NameDescription
TINY_MAIN_DIRPath to the PARENT folder of the TinyORM source folder.
TINY_BUILD_TREEPath to the current build tree - TINY_BUILD_TREE = $$shadowed($$PWD).

The TINY_MAIN_DIR is required for another features anyway (so it should already be set) and all that's left is to set the TINY_BUILD_TREE.

.qmake.conf
# Path to the current build tree (used to guess the TinyORM build tree)
TINY_BUILD_TREE = $$shadowed($$PWD)

If you will follow this pattern or logic then you can switch QtCreator Kits and the TINYORM_BUILD_TREE will be auto-generated correctly and will always point to the correct TinyORM build tree.

It works this way, all is happening inside the variables.pri, it takes a build folder name for the current project eg. build-HelloWorld-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug, replaces the HelloWorld with the TinyORM and as we already know the TinyORM build folder location we can simply concatenate these paths like $$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug.

caution

This will only work if you follow the recommended Folders structure.

Manual configuration internals

There is not much to say about the Manual configuration feature. It uses conf.pri files (there are four, one for every project or sub-project), and every project has prepared its own conf.pri.example file for faster initial configuration.

These conf.pri.example files are nicely commented on, so you can see what needs to be modified. The conf.pri files are loaded as late as possible, and they can be used to override the qmake configuration.

If the Auto-configuration feature is disabled and there are no conf.pri files, then the TinyORM qmake configuration or build will fail at 100%.

These conf.pri files are intended for configuring qmake's INCLUDEPATH and LIBS, CONFIG or eg. QMAKE_LFLAGS, or any other qmake options or variables.

Ccache support

The TinyORM supports the ccache out of the box for all supported compilers. For qmake you can enable it using the CONFIG+=ccache on Linux or CONFIG+=tiny_ccache_win32 on Windows. For CMake you can set the CMAKE_CXX_COMPILER_LAUNCHER=ccache.

On Linux it's clear, the ccache is fully supported and works also with the precompiled headers. But was necessary to add some workarounds to the qmake/CMake build systems to make out of the box support on Windows. When you enable the ccache on Windows then the build system disables precompiled headers and replaces the -Zi compiler option with the -Z7 (link to the issue).

tip

You can install the ccache using the scoop install ccache command on Windows.

- +../%{Project:Name}-builds-%{BuildSystem:Name}/%{JS: Util.asciify("build-%{Project:Name}-%{Kit:FileSystemName}-%{BuildConfig:Name}")}

Getting started

Prepare compilation environment, we need to put the Qt Framework and Visual Studio MSVC compiler on the path on Windows. The compiler is already on the path on Linux and you can export PATH and LD_LIBRARY_PATH for Qt Framework, or use our qtenvX scripts described above.

mkdir 
cd
$env:Path = 'C:\Qt\6.7.0\msvc2019_64\bin;' + $env:Path
vcvars64.ps1
tip

You can also use the tools/Add-FolderOnPath.ps1 pwsh script to fastly prepend a path or pwd on the system PATH.

vcpkg

Installing the vcpkg is highly recommended, it simplifies installation of the range-v3 and tabulate dependencies.

git clone git@github.com:microsoft/vcpkg.git
cd vcpkg
.\bootstrap-vcpkg.bat

Add vcpkg on the system path, add the following to the .bashrc or .zshrc on Linux.

export PATH=/vcpkg${PATH:+:}$PATH

On Windows, open the Environment variables dialog and add vcpkg on the user PATH.

Or you can export it for the current session only.

$env:Path = "\vcpkg;" + $env:Path

Set up vcpkg environment

To export vcpkg environment variables globally, add it to the .bashrc or .zshrc on Linux, and you can use the Environment variables dialog on Windows.

Linux
export VCPKG_DEFAULT_TRIPLET=x64-linux
#export VCPKG_DEFAULT_HOST_TRIPLET=x64-linux
export VCPKG_MAX_CONCURRENCY=11
export VCPKG_OVERLAY_PORTS="$HOME/.local/share/vcpkg/ports"
export VCPKG_OVERLAY_TRIPLETS="$HOME/.local/share/vcpkg/triplets"
export VCPKG_ROOT="$HOME/Code/c/vcpkg"
info

It is recommended to define these variables globally because the CMake and qmake build system are able to detect the vcpkg installation from them so you don't have to configure them manually to detect the vcpkg installation.

tip

On Windows, it's always better to create these types of variables as user variables instead of system variables in the Environment variables dialog.

C preprocessor macros

The following table summarizes all the C preprocessor macros defined in the TinyORM library. These C macros are configured by CMake or qmake build systems. They are not sorted alphabetically, but they are sorted by how significant they are.

In the CMake build system, all the C macros are auto-detected / auto-configured or controlled by CMake build options, so you don't have to care too much about them.

In the qmake build is important whether you are building TinyORM library or you are building your application and linking against TinyORM library. When you are building the TinyORM library, all the C macros are auto-detected / auto-configured or controlled by qmake build options, so you don't have to care too much about them.

But a special situation is when you are building your application / library and you are linking against TinyORM library. In this particular case, you must configure all these C macros manually! For this reason, the TinyOrm.pri has been created, so that's not a big deal either. Little more info here.

C Macro NameDescription
TINYORM_LINKING_SHAREDMust be defined when you are linking against TinyORM shared build (dll library), exported classes and functions will be tagged with __declspec(dllimport) on msvc and visibility("default") on GCC >= 4.
TINYORM_BUILDING_SHAREDDefined when TinyORM is built as a dll library (shared build).
TINYORM_DEBUGDefined in the debug build.
TINYORM_NO_DEBUGDefined in the release build.
TINYORM_DEBUG_SQLDefined in the debug build.
TINYORM_NO_DEBUG_SQLDefined in the release build.
TINYORM_MYSQL_PINGEnable Orm::MySqlConnection::pingDatabase() method.
Defined when mysql_ping (qmake) / MYSQL_PING (cmake) configuration build option is enabled.
TINYORM_DISABLE_ORMControls the compilation of all ORM-related source code, when this macro is defined, then only the query builder without ORM is compiled. Also excludes ORM-related unit tests.
Defined when disable_orm (qmake) / ORM (cmake) configuration build option is enabled (qmake) / disabled (cmake).
TINYORM_EXTERN_CONSTANTSDefined when extern constants are used. Extern constants are enabled by default for shared builds and disabled for static builds.
Described at qmake / CMake how it works.
TINYORM_INLINE_CONSTANTSDefined when global inline constants are used.
Defined when inline_constants (qmake) / INLINE_CONSTANTS (cmake) configuration build option is enabled.
TINYORM_TESTS_CODEEnable code needed by unit tests, eg. connection overriding in the Orm::Tiny::Model.
Defined when build_tests (qmake) / BUILD_TESTS (cmake) configuration build option is enabled.
TINYORM_DISABLE_THREAD_LOCALRemove all thread_local storage duration specifiers, it disables multi-threading support.
Defined when disable_thread_local (qmake) / DISABLE_THREAD_LOCAL (cmake) configuration build option is enabled.
TINYTOM_MIGRATIONS_DIRDefault migrations path for the make:migration command, can be an absolute or relative path (to the pwd).
Default value: database/migrations (relative to the pwd)
Defined by TOM_MIGRATIONS_DIR (cmake) configuration build option.
(qmake note) You can use DEFINES += TINYTOM_MIGRATIONS_DIR="\"database/migrations\"" on the command-line or set it in the main conf.pri file.
TINYTOM_MODELS_DIRDefault models path for the make:model command, can be an absolute or relative path (to the pwd).
Default value: database/models (relative to the pwd)
Defined by TOM_MODELS_DIR (cmake) configuration build option.
(qmake note) You can use DEFINES += TINYTOM_MODELS_DIR="\"database/models\"" on the command-line or set it in the main conf.pri file.
TINYTOM_SEEDERS_DIRDefault seeders path for the make:seeder command, can be an absolute or relative path (to the pwd).
Default value: database/seeders (relative to the pwd)
Defined by TOM_SEEDERS_DIR (cmake) configuration build option.
(qmake note) You can use DEFINES += TINYTOM_SEEDERS_DIR="\"database/seeders\"" on the command-line or set it in the main conf.pri file.
TINYORM_USING_PCHDefined if building with precompiled headers.
Controlled by qmake / CMake.

Building with CMake

tip

If something is not clear, you can still look at GitHub Action workflows how a building is done.

First, create a basic folder structure and then clone the TinyORM project.

cd 
mkdir /TinyORM/TinyORM-builds-cmake/build-debug

cd /TinyORM
git clone git@github.com:silverqx/TinyORM.git

Configure & Build (cmake)

Now you are ready to configure the TinyORM library.

cd TinyORM-builds-cmake/build-debug
cmake.exe `
-S "/TinyORM/TinyORM" `
-B "/TinyORM/TinyORM-builds-cmake/build-debug" `
-G 'Ninja' `
-D CMAKE_BUILD_TYPE:STRING='Debug' `
-D CMAKE_TOOLCHAIN_FILE:FILEPATH="/vcpkg/scripts/buildsystems/vcpkg.cmake" `
-D CMAKE_INSTALL_PREFIX:PATH="/tmp/TinyORM" `
-D BUILD_TESTS:BOOL=OFF `
-D MATCH_EQUAL_EXPORTED_BUILDTREE:BOOL=ON `
-D MYSQL_PING:BOOL=OFF `
-D TOM:BOOL=ON `
-D TOM_EXAMPLE:BOOL=OFF `
-D VERBOSE_CONFIGURE:BOOL=ON
CMake STRICT_MODE option

The STRICT_MODE CMake configuration option was added in TinyORM v0.37.1. This option was added to avoid the propagation of aggressive strict warning compiler/linker options and Qt definitions from the TinyORM library to user code through the TinyOrm::CommonConfig interface library.

TinyORM uses the strictest warning level options, virtually anything that can be enabled is enabled to produce a better code. I highly recommend enabling this option to produce better code and to follow good practices. It also helps to follow the ISOCPP C++ Core Guidelines standards.

If you want to enable these strict warning options in your code, you can enable the STRICT_MODE CMake configuration option and they will be propagated to your code. You can also enabled it globally using the TINYORM_STRICT_MODE environment variable, and the value of this environment variable will be picked up during initial CMake configuration as the default value for the STRICT_MODE CMake configuration option.

You can achieve the same result by manually linking against the TinyOrm::CommonConfig interface library when the STRICT_MODE is set to OFF.

target_link_libraries(<target> PRIVATE TinyOrm::CommonConfig)
info

The recommended way is to set the TINYORM_STRICT_MODE environment variable to 1 or ON.

Build TinyORM

And build. You don't have to install it, you can use the build tree directly if you want.

cmake --build . --target all
cmake --install .

Or build and install in one step.

cmake --build . --target install
info

CMake multi-config generators like Ninja Multi-Config or Visual Studio 16 2019 are also supported.

CMake build options

Option NameDefaultDescription
BUILD_DRIVERSOFFBuild TinyDrivers SQL database drivers (core/common code; replaces QtSql module).
BUILD_MYSQL_DRIVERSOFFBuild TinyDrivers MySQL database driver.
Available when: BUILD_DRIVERS
BUILD_SHARED_LIBSONBuild as a shared/static library.
BUILD_TESTSOFFBuild TinyORM unit tests.
BUILD_TREE_DEPLOYONCopy TinyDrivers and TinyMySql libraries to the root of the build tree.
DRIVERS_TYPESharedHow to build and link against TinyDrivers SQL database drivers.
The Static value will be select by default when the BUILD_SHARED_LIBS is OFF.
Supported values: Shared, Loadable, and Static
Available when: BUILD_DRIVERS AND BUILD_SHARED_LIBS
INLINE_CONSTANTSOFFUse inline constants instead of extern constants in the shared build.
OFF is highly recommended for the shared build;
is always ON for the static build.
Available when: BUILD_SHARED_LIBS
MSVC_RUNTIME_DYNAMICONUse MSVC dynamic runtime library (-MD) instead of static (-MT), also considers a Debug configuration (-MTd, -MDd).
Available when: MSVC AND NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY
MYSQL_PINGOFFEnable Orm::MySqlConnection::pingDatabase() method.
ORMONControls the compilation of all ORM-related source code, when this option is disabled, then only the query builder without ORM is compiled. Also excludes ORM-related unit tests.
STRICT_MODEOFFControls propagation of strict compiler/linker options and Qt definitions using the TinyOrm::CommonConfig interface library to the user code.
(highly recommended; can also be set with the TINYORM_STRICT_MODE environment variable; described here).
TOMONControls the compilation of all Tom-related source code, when this option is disabled, then it also excludes Tom-related unit tests.
TOM_EXAMPLEOFFBuild the tom console application example.
TOM_MIGRATIONS_DIR-Default migrations path for the make:migration command, can be an absolute or relative path (to the pwd).
Default value: database/migrations (relative to the pwd)
TOM_MODELS_DIR-Default models path for the make:model command, can be an absolute or relative path (to the pwd).
Default value: database/models (relative to the pwd)
TOM_SEEDERS_DIR-Default seeders path for the make:seeder command, can be an absolute or relative path (to the pwd).
Default value: database/seeders (relative to the pwd)
VERBOSE_CONFIGUREOFFShow information about PACKAGES_FOUND / PACKAGES_NOT_FOUND in the CMake configure output.

Advanced TinyORM options.

Option NameDefaultDescription
DISABLE_THREAD_LOCALOFFRemove all thread_local storage duration specifiers, it disables multi-threading support.
MATCH_EQUAL_EXPORTED_BUILDTREEOFFExported package configuration from the build tree is considered to match only when the build type of application/library that is linking against the TinyORM library is equal.
Available when:
CMAKE_EXPORT_PACKAGE_REGISTRY AND NOT TINY_IS_MULTI_CONFIG

Important CMake options.

Option NameDefaultDescription
CMAKE_DISABLE_PRECOMPILE_HEADERSOFFDisable precompiled headers.
CMAKE_CXX_COMPILERautoThe full path to the C++ compiler.
CMAKE_CXX_COMPILER_LAUNCHER-Default compiler launcher to use for the C++ compiler.
Can be used to enable ccache, eg. ccache.exe on MinGW or /usr/bin/ccache on Linux.
CMAKE_EXPORT_PACKAGE_REGISTRYONEnable the export(TinyOrm) command.
TinyORM sets this variable to ON by default.
CMAKE_VERBOSE_MAKEFILEOFFEnable verbose output from Makefile builds.

Consume TinyOrm library (cmake)

In your application or library CMakeLists.txt file add following find_package() call.

CMakeLists.txt
find_package(TinyOrm 0.37.1 CONFIG REQUIRED)

If the TinyORM build tree is not exported to the CMake's User Package Registry then also add the TinyORM build tree or CMAKE_INSTALL_PREFIX folder to the CMAKE_PREFIX_PATH, so CMake can find TinyORM's package configuration file during find_package(TinyOrm) call.

# build tree
list(APPEND CMAKE_PREFIX_PATH "/TinyORM/TinyORM-builds-cmake/build-debug")

# installation folder - CMAKE_INSTALL_PREFIX
list(APPEND CMAKE_PREFIX_PATH "/tmp/TinyORM")

Or as an alternative, you can set CMAKE_PREFIX_PATH environment variable.

As the last thing, do not forget to add TinyOrm0d.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so your application can find it during execution.

$env:Path = "\TinyORM\TinyORM-builds-cmake\build-debug;" + $env:Path

Now you can try the HelloWorld CMake example.

info

You can also try the FetchContent method to fastly link against the TinyORM library.

Building with qmake

First, create a basic folder structure and then clone the TinyORM project.

cd 
mkdir /TinyORM/TinyORM-builds-qmake

cd /TinyORM
git clone git@github.com:silverqx/TinyORM.git

Install dependencies

With the qmake build system, you have to install TinyORM dependencies manually. We will use the vcpkg package manager.

cd ../../vcpkg

vcpkg search range-v3
vcpkg search tabulate
vcpkg install range-v3 tabulate
vcpkg list

On Linux, you can install the range-v3 library and some other dependencies with the package manager.

Configure & Build (qmake)

Open QtCreator IDE

tip

I recommend creating a new Session in the QtCreator, this way you will have all the examples in one place and as a bonus, everything will be in the same place when you close and reopen QtCreator IDE. You can name it tinyorm.org or TinyORM examples, it is up to you.

tip

If you are using sessions, you can use a single clangd instance for all projects in this session in the QtCreator IDE. One significant advantage of this method is that the .qtc_clangd/ folder will not be created in the build folder, but will be stored globally in the Roaming profile. You can enable it in the Settings - C++ - Clangd - Sessions with a single clangd instance.

Configure TinyORM

Now you are ready to configure the TinyORM library. There are two ways how to configure the TinyORM library and it's the new Auto-configure feature added in TinyORM v0.34.0 using the .env files and the old way using the conf.pri files.

Auto-configuration and tiny_dotenv

This is the new recommended method to auto-configure TinyORM's qmake build system and also the dependencies, it was added in TinyORM v0.34.0. You need to copy the prepared .env.(win32|unix|mingw).example file to the .env.(win32|unix|mingw). One .env example file is prepared for each supported platform.

All prepared .env.(win32|unix|mingw).example files are simple and clear. You can also create a common .env file that is included before the platform-specific .env.(win32|unix|mingw) files.

cd /TinyORM/TinyORM

cp .env.win32.example .env.win32

And that is all, if you have correctly set all qmake variables in this .env.(win32|unix|mingw) file or you have correctly set environment variables, then the qmake build system should be able to auto-detect all dependencies . 🔥

info

The Auto-configuration and Environment files internals are described at the end to make this section more clear.

tip

The Auto-configuration feature can be turned off using the disable_autoconf qmake configuration option (eg. CONFIG*=disable_autoconf).

tip

The tiny_dotenv feature can be turned off using the disable_dotenv qmake configuration option (eg. CONFIG*=disable_dotenv).

Manual configuration (conf.pri)

This is the old method used before TinyORM v0.34.0. You need to copy the conf.pri.example files to conf.pri (there are four, one for every project or sub-project) and manually update the INCLUDEPATH and LIBS to configure TinyORM's qmake build dependencies. This way you can override any qmake build options or variables.

To disable the Auto-configuration feature you must define the disable_autoconf qmake configuration option (eg. CONFIG*=disable_autoconf) because from TinyORM v0.34.0 is the Auto-configuration feature enabled by default.

You can also remove all .env files or turn off the tiny_dotenv feature using CONFIG*=disable_dotenv. You can use them all at once if you want, .env and also conf.pri files.

conf.pri files are nicely commented on, so you can see what needs to be modified.

cd /TinyORM/TinyORM

cp conf.pri.example conf.pri
cp tests/conf.pri.example tests/conf.pri
cp tests/testdata_tom/conf.pri.example tests/testdata_tom/conf.pri
cp examples/tom/conf.pri.example examples/tom/conf.pri
info

The Manual configuration internals are described at the end to make this section more clear.

note

The Manual configuration is still relevant if you have any non-standard installation of the vcpkg or MySQL and the Auto-configuration feature fails.

Opening TinyORM.pro (main project file)

Now you can open the TinyORM.pro project in the QtCreator IDE.

This will open the Configure Project tab, select some kit and update build folder paths to meet our folders structure or like you want.

TinyORM - QtCreator - Configure Project
tip

You can force the QtCreator to generate a build folders structure as is described above.

You are ready to configure build options, hit Ctrl+5 to open Project Settings tab and select Build in the left sidebar to open the Build Settings, it should look similar to the following picture.

Disable QML debugging and profiling and Qt Quick Compiler, they are not used.

TinyORM - QtCreator - Build Settings

If you want to change some TinyORM build options, you can pass them to the Build Steps - qmake TinyORM.pro - Additional arguments input field. It can look like this.

TinyORM - QtCreator - Build Settings - Additional arguments

Build TinyORM

Everything is ready for build, you can press Ctrl+b to build the project.

qmake build options

CONFIG Option NameDefaultDescription
build_loadable_driversOFFBuild TinyDrivers as a shared library and SQL database drivers (eg. TinyMySql) as shared libraries (Loadable modules) that are loaded at runtime using LoadLibrary() on Windows or dlopen() on Linux.
build_mysql_driverOFFBuild TinyDrivers MySQL database driver.
It's enabled by default when build_shared_drivers, build_loadable_drivers, or build_static_drivers is enabled.
Available when: build_shared_drivers OR build_loadable_drivers OR build_static_drivers
build_shared_driversOFFBuild TinyDrivers as a Shared library.
build_static_driversOFFBuild TinyDrivers as a Static library archive.
The build_static_drivers qmake configuration option will be select by default when the CONFIG*=staticlib is enabled.
build_testsOFFBuild TinyORM unit tests.
disable_autoconfOFFDisable the Auto-configuration feature (auto-configuration is enabled by default from TinyORM v0.34.0).
disable_dotenvOFFDisable the tiny_dotenv feature (environment files are enabled by default from TinyORM v0.34.0).
disable_thread_localOFFRemove all thread_local storage duration specifiers, it disables multi-threading support.
disable_ormOFFControls the compilation of all ORM-related source code, when this option is enabled, then only the query builder without ORM is compiled. Also excludes ORM-related unit tests.
disable_tomOFFControls the compilation of all Tom-related source code, when this option is disabled, then it also excludes Tom-related unit tests.
extern_constantsONUse extern constants instead of inline constants in the shared build.
ON is highly recommended for the shared build (by default);
is always OFF for the static build.
Available when: CONFIG(shared|dll):!inline_constants
inline_constantsOFFUse inline constants instead of extern constants in the shared build.
OFF is highly recommended for the shared build;
is always ON for the static build.
mysql_pingOFFEnable Orm::MySqlConnection::pingDatabase() method.
tiny_ccache_win32ONEnable compiler cache. Homepage
It works only on Windows systems. It works well with the MSYS2 g++, clang++, msvc, and clang-cl with msvc. It disables precompile_header as they are not supported on Windows and changes the -Zi compiler option to the -Z7 for debug builds as the -Zi compiler option is not supported (link to the issue).
tom_exampleOFFBuild the tom console application example.

Advanced TinyORM options.

Option NameDefaultDescription
ubsanOFFAllows to enable UBSan sanitizer (Clang only).

Important qmake options.

CONFIG Option NameDefaultDescription
ccacheOFFEnable compiler cache. Homepage
It works only on the Unix systems. It works well with the g++ and clang++ and also supports precompiled headers.
precompile_header-Enable precompiled headers, you can disable them with:
CONFIG-=precompile_header.
The precompile_header is enabled by default on msvc, g++, clang++, clang-cl on Windows and disabled by default on linux.
static
staticlib
OFFBuild as a static library (lib only).
If you want to build all libraries in the TinyORM project as static library archives and link against static libraries use the CONFIG += static. Don't use the CONFIG += staticlib.
See NOTES.txt for more information (search static vs staticlib).
static_runtimeOFFLink against the shared (dynamic) or static run-time library.
The -MD becomes -MT and -MDd becomes -MTd. It works only on MSVC and MinGW or MSYS2.
Please don't use this option.
Available when: msvc or mingw

Consume TinyOrm library (qmake)

The TinyOrm.pri file is available to simplify the integration of the TinyORM library into your application. It sets up and configures the CONFIG and DEFINES qmake variables, adds the TinyORM, tom, and vcpkg header files on the system INCLUDEPATH (cross-platform using the -isystem or -imsvc), links against the TinyORM shared or static library using the LIBS.

You can use it to configure the TinyORM library when you are linking against it. It does a very similar thing like the CMake's Find Modules feature.

Requirements

It has a few requirements, you need to:

  • specify path to the TinyORM qmake features (.prf files) using the QMAKEFEATURES variable that can only be set in the .qmake.conf file
  • specify qmake or environment variables to find the vcpkg installation (TINY_VCPKG_ROOT and TINY_VCPKG_TRIPLET)
  • specify path to the TinyORM build folder (TINYORM_BUILD_TREE)
  • build your application with the same CONFIG qmake variables that were used when building the TinyORM library

Let's explain one by one.

QMAKEFEATURES

Create the .qmake.conf file in your application root folder with the following content.

.qmake.conf
# Path to the PARENT folder of the TinyORM source folder
TINY_MAIN_DIR = $$clean_path(<your_path>)
# To find .env and .env.$$QMAKE_PLATFORM files in YOUR project
TINY_DOTENV_ROOT = $$PWD

# Path to the TinyORM build folder (specified manually)
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/)
# vcpkg - range-v3 and tabulate
TINY_VCPKG_ROOT = $$quote(<your_path>/vcpkg/)
#TINY_VCPKG_TRIPLET = x64-windows

# To find .prf files, needed by eg. CONFIG += tiny_system_headers inline/extern_constants
QMAKEFEATURES *= $$quote($$TINY_MAIN_DIR/TinyORM/qmake/features)

You can move all qmake variables that are part of the qmake configuration process to the .env file if you want (recommended), this is possible because the TinyOrm.pri enables the Environment files feature by default.

You can look at the Auto-configure using .qmake.conf and .env example for Hello world project of what must stay in the qmake.conf file and what can be moved to the .env files.

tip

You can use the Partial guessing of the TINYORM_BUILD_TREE if you don't like to specify it manually.

Variables affecting TinyOrm.pri

You must define the following variables before the TinyOrm.pri is included:

Variable NameDescription
TINYORM_BUILD_TREEPath to the TinyORM build folder.
TINY_VCPKG_ROOTPath to the vcpkg installation folder.
If not defined, then it tries to use the VCPKG_ROOT environment variable.
TINY_VCPKG_TRIPLETThe vcpkg triplet to use (vcpkg/installed/$$TINY_VCPKG_TRIPLET/).
If not defined, then it tries to guess the vcpkg triplet based on the current compiler and OS (based on the QMAKESPEC), and as the last thing, it tries to use the VCPKG_DEFAULT_TRIPLET environment variable.

These variables will be set after the configuration is done:

Variable NameDescription
TINY_BUILD_SUBFOLDERFolder by release type if CONFIG+=debug_and_release is defined (/debug, /release, or an empty string).
TINY_CCACHE_BUILDTo correctly link ccache build against a ccache build (_ccache or an empty string).
TINY_MSVC_VERSIONThe msvc compiler string (MSVC2022 or MSVC2019).
TINY_QT_VERSION_UNDERSCOREDUnderscored Qt version (eg. 6_7_0).
TINY_RELEASE_TYPE_CAMELBuild type string (Debug, Profile, or Release).
TINY_VCPKG_INCLUDEPath to the vcpkg include folder (vcpkg/installed/<triplet>/include/).

Then you simply include the TinyOrm.pri in your project file.

AnyProject.pro
include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)

And that is all, now you should be able to link against the TinyORM library. 👌

Manual configuration examples

Frankly, there is no reason to use the Manual configuration (define the variables described below before the TinyOrm.pri inclusion), the only reason to use it is when you want more control over this process or want to define everything yourself. I'll leave this section here to show how things work.

You will have to link against the TinyORM library manually if you don't set the TINYORM_BUILD_TREE qmake variable before the inclusion of the TinyOrm.pri file. The INCLUDEPATH is auto-detected every time.

# Link against TinyORM library
# ---
TINY_MAIN_DIR = $$clean_path(<your_path>)

# Configure TinyORM library
include($$TINY_MAIN_DIR/TinyORM/qmake/TinyOrm.pri)

# TinyORM library path
TINYORM_BUILD_TREE = $$quote($$TINY_MAIN_DIR/TinyORM-builds-qmake)
LIBS += $$quote(-L$$TINYORM_BUILD_TREE/build-TinyORM-Desktop_Qt_6_7_0_MSVC2019_64bit-Debug/src$${TINY_BUILD_SUBFOLDER}/)
LIBS += -lTinyOrm

The same is true for the vcpkg include path. If you don't set the TINY_VCPKG_ROOT or have not defined the VCPKG_ROOT environment variable, then you need to set up the INCLUDEPATH for the vcpkg that provides the range-v3 and tabulate header files.

# vcpkg - range-v3 and tabulate
# ---
INCLUDEPATH += $$quote(<your_path>/vcpkg/installed/x64-windows/include/)

You can also use TinyORM's qmake function tiny_add_system_includepath() which handles INCLUDEPATH in a cross-platform way.

# vcpkg - range-v3 and tabulate
# ---
load(tiny_system_includepath)
tiny_add_system_includepath(<your_path>/vcpkg/installed/x64-linux/include/)

Do not forget to add TinyOrm0.dll on the path on Windows and on the LD_LIBRARY_PATH on Linux, so your application can find it during execution.

$env:Path = "\TinyORM\TinyORM-builds-qmake\build-debug;" + $env:Path
tip

On Linux -isystem marks the directory as a system directory, it prevents warnings.

On Windows you can use QMAKE_CXXFLAGS_WARN_ON = -external:anglebrackets -external:W0, it applies a warning level 0 to the angel bracket includes; #include <file>.

With the clang-cl with MSVC you can use -imsvc.

Auto-configuration internals

The qmake build system does not support auto-configuration of dependencies out of the box but TinyORM from v0.34.0 added its own Auto-configuration feature along with the tiny_dotenv qmake feature. These new features allow us to auto-configure TinyORM project, and with their help, the conf.pri files can be skipped entirely.

While it adds additional complexity to the qmake configuration process, the benefits are significant.

The Auto-configuration feature is designed to find the vcpkg and MySQL installations, and tiny_dotenv to include the .env and .env.(win32|unix|mingw) files in the project's root folder. These new features can be configured using qmake and environment variables, and they also contain some guessing logic if these variables are not defined.

The Auto-configuration feature can be turned off using the disable_autoconf qmake configuration option (eg. CONFIG*=disable_autoconf).

These are qmake and environment variables that affect the Auto-configuration feature:

Variable NameDescription
TINY_VCPKG_ROOTPath to the vcpkg installation folder.
If not defined, then it tries to use the VCPKG_ROOT environment variable.
TINY_VCPKG_TRIPLETThe vcpkg triplet to use (vcpkg/installed/$$TINY_VCPKG_TRIPLET/).
If not defined, then it tries to guess the vcpkg triplet based on the current compiler and OS (based on the QMAKESPEC), and as the last thing, it tries to use the VCPKG_DEFAULT_TRIPLET environment variable.
TINY_MYSQL_ROOTPath to the MySQL installation folder.
If not defined, then it tries to guess the MySQL installation folder (win32 only): $$(ProgramFiles)/MySQL/MySQL Server (8.3|8.2|8.1|8.0|5.7)/

You can set these variables in the .env (recommended) or conf.pri files, in the .qmake.conf file (or wherever you want), or as environment variables.

These variables will be set after auto-configuration is done:

Variable NameDescription
TINY_VCPKG_INCLUDEPath to the vcpkg include folder (vcpkg/installed/<triplet>/include/).
TINY_MYSQL_INCLUDEPath to the MySQL include folder (MySQL Server 8.3/include/).
TINY_MYSQL_LIBPath to the MySQL lib folder (MySQL Server 8.3/lib/).

The TINY_MYSQL_INCLUDE and TINY_MYSQL_LIB are only set on win32 platform except mingw.

Environment files

The tiny_dotenv feature allows us to define the .env and .env.$$TINY_DOTENV_PLATFORM files in the project's root folder. These files are loaded as early as possible so you can affect the qmake configuration process. On the other hand, the conf.pri files are loaded as late as possible, and they can be used to override the qmake configuration.

The .env file is included first and is included on all platforms.

There is only one requirement for this feature to work correctly, and that is to set the TINY_DOTENV_ROOT qmake variable to the project's root folder. This variable is already set in the .qmake.conf file for the TinyORM project.

Then the following names are taken into account: .env, .env.win32, .env.unix, .env.mingw

.qmake.conf
# To find .env and .env.$$QMAKE_PLATFORM files
TINY_DOTENV_ROOT = $$PWD

The tiny_dotenv feature can be turned off using the disable_dotenv qmake configuration option (eg. CONFIG*=disable_dotenv).

caution

Environment files don't work in the CMake builds.

Partial guessing of the TINYORM_BUILD_TREE

You don't have to manually define the TINYORM_BUILD_TREE in .env or .qmake.conf files. The TINYORM_BUILD_TREE absolute path can be put together for you (this is happening inside the variables.pri file) and TinyORM build folder name can be guessed for you too.

You must define the following variables before the TinyOrm.pri will be included to make this real (set them in the .qmake.conf):

Variable NameDescription
TINY_MAIN_DIRPath to the PARENT folder of the TinyORM source folder.
TINY_BUILD_TREEPath to the current build tree - TINY_BUILD_TREE = $$shadowed($$PWD).

The TINY_MAIN_DIR is required for another features anyway (so it should already be set) and all that's left is to set the TINY_BUILD_TREE.

.qmake.conf
# Path to the current build tree (used to guess the TinyORM build tree)
TINY_BUILD_TREE = $$shadowed($$PWD)

If you will follow this pattern or logic then you can switch QtCreator Kits and the TINYORM_BUILD_TREE will be auto-generated correctly and will always point to the correct TinyORM build tree.

It works this way, all is happening inside the variables.pri, it takes a build folder name for the current project eg. build-HelloWorld-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug, replaces the HelloWorld with the TinyORM and as we already know the TinyORM build folder location we can simply concatenate these paths like $$TINY_MAIN_DIR/TinyORM-builds-qmake/build-TinyORM-Desktop_Qt_6_7_0_MSVC2022_64bit-Debug.

caution

This will only work if you follow the recommended Folders structure.

Manual configuration internals

There is not much to say about the Manual configuration feature. It uses conf.pri files (there are four, one for every project or sub-project), and every project has prepared its own conf.pri.example file for faster initial configuration.

These conf.pri.example files are nicely commented on, so you can see what needs to be modified. The conf.pri files are loaded as late as possible, and they can be used to override the qmake configuration.

If the Auto-configuration feature is disabled and there are no conf.pri files, then the TinyORM qmake configuration or build will fail at 100%.

These conf.pri files are intended for configuring qmake's INCLUDEPATH and LIBS, CONFIG or eg. QMAKE_LFLAGS, or any other qmake options or variables.

Ccache support

The TinyORM supports the ccache out of the box for all supported compilers. For qmake you can enable it using the CONFIG+=ccache on Linux or CONFIG+=tiny_ccache_win32 on Windows. For CMake you can set the CMAKE_CXX_COMPILER_LAUNCHER=ccache.

On Linux it's clear, the ccache is fully supported and works also with the precompiled headers. But was necessary to add some workarounds to the qmake/CMake build systems to make out of the box support on Windows. When you enable the ccache on Windows then the build system disables precompiled headers and replaces the -Zi compiler option with the -Z7 (link to the issue).

tip

You can install the ccache using the scoop install ccache command on Windows.

+ \ No newline at end of file diff --git a/database/getting-started.html b/database/getting-started.html index 4f76c53f0..06a129976 100644 --- a/database/getting-started.html +++ b/database/getting-started.html @@ -14,13 +14,13 @@ - +

Database: Getting Started

Introduction

Almost every modern application interacts with a database. TinyORM makes interacting with a database extremely simple using raw SQL, a fluent query builder, and the TinyORM. Currently, TinyORM provides first-party support for four databases:

TinyORM internally uses QtSql module, you can look for supported databases.

note

TinyORM's code is ready and designed to simply add support for the SQL Server.

Configuration

You can create and configure a new database connection using the create method provided by the DB facade:

#include <orm/db.hpp>

using Orm::DB;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QMYSQL"},
{"host", qEnvironmentVariable("DB_HOST", "127.0.0.1")},
{"port", qEnvironmentVariable("DB_PORT", "3306")},
{"database", qEnvironmentVariable("DB_DATABASE", "")},
{"username", qEnvironmentVariable("DB_USERNAME", "root")},
{"password", qEnvironmentVariable("DB_PASSWORD", "")},
{"charset", qEnvironmentVariable("DB_CHARSET", "utf8mb4")},
{"collation", qEnvironmentVariable("DB_COLLATION", "utf8mb4_0900_ai_ci")},
{"timezone", "+00:00"},
/* Specifies what time zone all QDateTime-s will have, the overridden default is
the Qt::UTC, set to the Qt::LocalTime or QtTimeZoneType::DontConvert to use
the system local time. */
{"qt_timezone", QVariant::fromValue(Qt::UTC)},
{"prefix", ""},
{"prefix_indexes", false},
{"strict", true},
{"engine", "InnoDB"},
{"options", QVariantHash()},
});
#include <orm/db.hpp>
#include <orm/utils/configuration.hpp>

using Orm::DB;

using ConfigUtils = Orm::Utils::Configuration;

using namespace Orm::Constants; // NOLINT(google-build-using-namespace)

// Ownership of a shared_ptr()
auto manager = DB::create({
{driver_, QMYSQL},
{host_, qEnvironmentVariable("DB_HOST", H127001)},
{port_, qEnvironmentVariable("DB_PORT", P3306)},
{database_, qEnvironmentVariable("DB_DATABASE", EMPTY)},
{username_, qEnvironmentVariable("DB_USERNAME", ROOT)},
{password_, qEnvironmentVariable("DB_PASSWORD", EMPTY)},
{charset_, qEnvironmentVariable("DB_CHARSET", UTF8MB4)},
{collation_, qEnvironmentVariable("DB_COLLATION", UTF8MB40900aici)},
// SSL-related
{ssl_ca, QStringLiteral("C:/mysql/data/ca.pem")},
{ssl_cert, QStringLiteral("C:/mysql/data/client-cert.pem")},
{ssl_key, QStringLiteral("C:/mysql/data/client-key.pem")},
{ssl_mode, VerifyCA},
// Or
// {options, ConfigUtils::mysqlSslOptions()},
{timezone_, TZ00},
/* Specifies what time zone all QDateTime-s will have, the overridden default is
the Qt::UTC, set to the Qt::LocalTime or QtTimeZoneType::DontConvert to use
the system local time. */
{qt_timezone, QVariant::fromValue(Qt::UTC)},
{prefix_, EMPTY},
{prefix_indexes, false},
{strict_, true},
// {isolation_level, QStringLiteral("REPEATABLE READ")}, // MySQL default is REPEATABLE READ for InnoDB
{engine_, InnoDB},
{Version, {}}, // Autodetect
{options_, QVariantHash()},
// Examples
// {options_, QStringLiteral("MYSQL_OPT_CONNECT_TIMEOUT = 1 ; MYSQL_OPT_READ_TIMEOUT=1")},
// {options_, QVariantHash {{QStringLiteral("MYSQL_OPT_CONNECT_TIMEOUT"), 1},
// {QStringLiteral("MYSQL_OPT_READ_TIMEOUT"), 1}}},
});

The first argument is configuration hash which is of type QVariantHash and the second argument specifies the name of the connection, this connection will also be a default connection. You can configure multiple database connections at once and choose the needed one before executing SQL query, section Using Multiple Database Connections describes how to create and use multiple database connections.

You may also configure connection options by options key as QVariantHash or QString, you can pass any connection options supported by QSqlDatabase.

You can also configure Transaction Isolation Levels for MySQL connection with the isolation_level configuration option.

The version option is relevant only for the MySQL connections and you can save/avoid one database query (select version()) if you provide it manually. On the base of this version will be decided which session variables will be set if strict mode is enabled and whether to use an alias during the upsert method call.

Breaking values are as follows; use an upsert alias on the MySQL >=8.0.19 and remove the NO_AUTO_CREATE_USER sql mode on the MySQL >=8.0.11 if the strict mode is enabled.

info

A database connection is resolved lazily, which means that the connection configuration is only saved after the DB::create method call. The connection will be resolved after you run some query or you can create it using the DB::connection method.

tip

You can also use predefined string constants to avoid unnecessary QString instantiations, as used in the tom migrations example.

SQLite Configuration

SQLite databases are contained within a single file on your filesystem. You can create a new SQLite database using the touch command in your terminal: touch database.sqlite3. After the database has been created, you may configure SQLite database connection:

#include <orm/db.hpp>

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QSQLITE"},
{"database", qEnvironmentVariable("DB_DATABASE", "/absolute/path/to/database.sqlite3")},
{"foreign_key_constraints", qEnvironmentVariable("DB_FOREIGN_KEYS", "true")},
{"check_database_exists", true},
{"prefix", ""},
});

The database configuration value is the absolute path to the database. To enable foreign key constraints for SQLite connections, you should set the foreign_key_constraints configuration value to true, if this configuration value is not set, then the default of the SQLite driver will be used (currently the default is disabled).

If the check_database_exists configuration value is set to the true value, then the database connection throws an Orm::InvalidArgumentError exception, when the SQLite database file doesn't exist. If it is set to the false value and the SQLite database file doesn't exist, then it will be created for you by SQLite driver. The default value is true.

SSL Connections

SSL connections are supported for the MySQL and PostgreSQL databases. They can be set using the options configuration option.

info

This feature is heavily dependent on the underlying QSqlDatabase module. What means that you can pass the same connection options to the TinyORM that the QSqlDatabase accepts.

MySQL

You have to pass the SSL_CA, SSL_CERT, SSL_KEY, and MYSQL_OPT_SSL_MODE options.

#include <orm/db.hpp>

using Orm::DB;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QMYSQL"},
{"host", qEnvironmentVariable("DB_MYSQL_HOST", "127.0.0.1")},
...
{"options", QVariantHash({{"SSL_CA", "C:/mysql/data/ca.pem"},
{"SSL_CERT", "C:/mysql/data/client-cert.pem"},
{"SSL_KEY", "C:/mysql/data/client-key.pem"},
{"MYSQL_OPT_SSL_MODE", "VERIFY_CA"}})},
});

You may also use the ConfigUtils::mysqlSslOptions() or the ConfigUtils::insertMySqlSslOptions() methods to insert these options for you and define them using the DB_MYSQL_SSL_CA, DB_MYSQL_SSL_CERT, DB_MYSQL_SSL_KEY, and DB_MYSQL_SSL_MODE environment variables.

#include <orm/db.hpp>
#include <orm/utils/configuration.hpp>

using Orm::DB;

using ConfigUtils = Orm::Utils::Configuration;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QMYSQL"},
{"host", qEnvironmentVariable("DB_MYSQL_HOST", "127.0.0.1")},
...
{"options", ConfigUtils::mysqlSslOptions()},
});

You can define these SSL-related options in the top-level configuration, they will be copied to the options option hash during configuration parsing. The top-level configuration takes precedence and overwrites the options in the options hash.

#include <orm/db.hpp>

using Orm::DB;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QMYSQL"},
{"host", qEnvironmentVariable("DB_MYSQL_HOST", "127.0.0.1")},
...
{"SSL_CA", "C:/mysql/data/ca.pem"},
{"SSL_CERT", "C:/mysql/data/client-cert.pem"},
{"SSL_KEY", "C:/mysql/data/client-key.pem"},
{"MYSQL_OPT_SSL_MODE", "VERIFY_CA"},
});
tip

You can take a look at the GitHub actions how the MySQL certificates are generated in the CI pipeline for Windows and Linux.

tip

You can also pass the QString to the options configuration separated by the ; semicolon character and use the = to assign values.

PostgreSQL

You have to pass the sslmode or the deprecated requiressl options.

#include <orm/db.hpp>

using Orm::DB;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QPSQL"},
{"host", qEnvironmentVariable("DB_PGSQL_HOST", "127.0.0.1")},
...
{"options", QVariantHash({{"sslmode", "verify-full"}})},
});

And place your client certificates to the ~/.postgres/ on Linux and $env:APPDATA/postgres/ on Windows. Everything is described in the PostgreSQL's libpq client and server documentation.

If you want to keep your client certificates in your own location, you can set the sslcert, sslkey, and sslrootcert options.

#include <orm/db.hpp>

using Orm::DB;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QPSQL"},
{"host", qEnvironmentVariable("DB_PGSQL_HOST", "127.0.0.1")},
...
{"options", QVariantHash({{"sslmode", "verify-full"},
{"sslcert", "C:/example/postgres.crt"},
{"sslkey", "C:/example/postgres.key"},
{"sslrootcert", "C:/example/root.crt"}})},
});

You can define these SSL-related options in the top-level configuration, they will be copied to the options option hash during a configuration parsing. The top-level configuration takes precedence and overwrites the options in the options hash.

#include <orm/db.hpp>

using Orm::DB;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QPSQL"},
{"host", qEnvironmentVariable("DB_PGSQL_HOST", "127.0.0.1")},
...
{"sslmode", "verify-full"},
{"sslcert", "C:/example/postgres.crt"},
{"sslkey", "C:/example/postgres.key"},
{"sslrootcert", "C:/example/root.crt"},
});

You may also use the ConfigUtils::postgresSslOptions() or the ConfigUtils::insertPostgresSslOptions() methods to insert the sslmode, sslcert, sslkey, and sslrootcert options for you and define them using the DB_PGSQL_SSLMODE, DB_PGSQL_SSLCERT, DB_PGSQL_SSLKEY, and DB_PGSQL_SSLROOTCERT environment variable.

#include <orm/db.hpp>
#include <orm/utils/configuration.hpp>

using Orm::DB;

using ConfigUtils = Orm::Utils::Configuration;

// Ownership of a shared_ptr()
auto manager = DB::create({
{"driver", "QPSQL"},
{"host", qEnvironmentVariable("DB_PGSQL_HOST", "127.0.0.1")},
...
{"options", ConfigUtils::postgresSslOptions()},
});
info

The PostgreSQL's libpq client library provides the PGSSLMODE, PGSSLCERT, PGSSLKEY, and PGSSLROOTCERT environment variables, so you don't have to use TinyORM's options configuration and may use these environment variables instead.

tip

You can take a look at the GitHub actions how the PostgreSQL certificates are generated in the CI pipeline for Windows and Linux.

Running SQL Queries

Once you have configured your database connection, you may run queries using the DB facade. The DB facade provides methods for each type of query: select, update, insert, delete, and statement.

Running A Select Query

To run a basic SELECT query, you may use the select method on the DB facade:

auto users = DB::select("select * from users where active = ?", {1});

The first argument passed to the select method is the SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the where clause constraints. Parameter binding provides protection against SQL injection.

The select method returns a QSqlQuery containing the results of the query, where each result can be accessed by QSqlQuery::next method. Look into the QSqlQuery documentation on how to obtain results from the "query". You may access each column's value by QSqlQuery::value method. The first bool return value is the value returned from QSqlQuery::exec method:

#include <QDebug>

#include <orm/db.hpp>

auto users = DB::select("select * from users");

while(users.next())
qDebug() << users.value("name").toString();

Selecting Scalar Values

Sometimes your database query may result in a single, scalar value. Instead of being required to retrieve the query's scalar result from a record instance, TinyORM allows you to retrieve this value directly using the scalar shortcut method:

#include <orm/db.hpp>

auto states = DB::scalar(
"select count(case when state = 'pending' then 1 end) as states "
"from comments"
);

// With binding
auto states = DB::scalar(
"select count(case when state = ? then 1 end) as states from comments",
{"pending"}
);

Running An Insert Statement

To execute an insert statement, you may use the insert method on the DB facade. Like select, this method accepts the SQL query as its first argument and bindings as its second argument and returns QSqlQuery:

#include <orm/db.hpp>

DB::insert("insert into users (id, name) values (?, ?)", {1, "Marc"});

Running An Update Statement

The update method should be used to update existing records in the database. The number of rows affected by the statement and QSqlQuery is returned by the method as std::tuple<int, QSqlQuery>:

#include <QDateTime>

#include <orm/db.hpp>

auto [affected, query] = DB::update(
"update users set updated_at = ? where name = ?",
{QDateTime::currentDateTimeUtc(), "Anita"}
);

if (!affected)
qDebug() << "Any record was updated.";

Running A Delete Statement

The remove method should be used to delete records from the database. Like update, the number of affected rows and QSqlQuery will be returned by the method as std::tuple<int, QSqlQuery>:

#include <orm/db.hpp>

auto [affected, query] = DB::remove("delete from users");
note

delete can not be used as the method name because it is the reserved word.

Running A General Statement

Some database statements do not return any value. For these types of operations, you may use the statement method on the DB facade:

DB::statement("drop table users");
tip

DB::statement method should be used for DDL queries, don't use it for "select" queries because it internally calls recordsHaveBeenModified method.

Running An Unprepared Statement

Sometimes you may want to execute an SQL statement without binding any values. You may use the DB facade's unprepared method to accomplish this:

DB::unprepared("update users set votes = 100 where name = 'Dries'");
caution

Since unprepared statements do not bind parameters, they may be vulnerable to SQL injection. You should never allow user controlled values within an unprepared statement.

Implicit Commits

When using the DB facade's statement methods within transactions, you must be careful to avoid statements that cause implicit commits. These statements will cause the database engine to indirectly commit the entire transaction, leaving TinyORM unaware of the database's transaction level. An example of such a statement is creating a database table:

DB::statement("create table users (name varchar(255) null)");

Please refer to the MySQL manual for a list of all statements that trigger implicit commits.

Using Multiple Database Connections

You can configure multiple database connections at once during DatabaseManager instantiation using the DB::create overload, where the first argument is a hash of multiple connections and is of type QHash<QString, QVariantHash> and the second argument is the name of the default connection:

#include <orm/db.hpp>

// Ownership of a shared_ptr()
auto manager = DB::create({
{"mysql", {
{"driver", "QMYSQL"},
{"host", qEnvironmentVariable("DB_MYSQL_HOST", "127.0.0.1")},
{"port", qEnvironmentVariable("DB_MYSQL_PORT", "3306")},
{"database", qEnvironmentVariable("DB_MYSQL_DATABASE", "")},
{"username", qEnvironmentVariable("DB_MYSQL_USERNAME", "root")},
{"password", qEnvironmentVariable("DB_MYSQL_PASSWORD", "")},
{"charset", qEnvironmentVariable("DB_MYSQL_CHARSET", "utf8mb4")},
{"collation", qEnvironmentVariable("DB_MYSQL_COLLATION", "utf8mb4_0900_ai_ci")},
{"strict", true},
{"options", QVariantHash()},
}},
{"sqlite", {
{"driver", "QSQLITE"},
{"database", qEnvironmentVariable("DB_SQLITE_DATABASE", "")},
{"foreign_key_constraints", qEnvironmentVariable("DB_SQLITE_FOREIGN_KEYS", "true")},
{"check_database_exists", true},
{"prefix", ""},
}},
}, "mysql");

If your application needs to use multiple connections, you may access each connection via the connection method provided by the DB facade. The connection name passed to the connection method should correspond to one of the connections key listed in your configuration:

#include <orm/db.hpp>

auto query = DB::connection("mysql_test").select(...);

You may access the raw underlying QSqlQuery instance of a connection using the getQtQuery method on a connection instance:

auto query = DB::connection().getQtQuery();

Or you can use the shortcut method qtQuery provided by the DB facade:

auto query = DB::qtQuery();

Database Transactions

Manually Using Transactions

If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method provided by the DB facade:

#include <orm/db.hpp>

DB::beginTransaction();

You can rollback the transaction via the rollBack method:

DB::rollBack();

Lastly, you can commit a transaction via the commit method:

DB::commit();

All transaction methods accept a connection name as the optional argument:

DB::beginTransaction("mysql_test");
tip

The DB facade's transaction methods control the transactions for both the query builder and TinyORM.

Multi-threading support

The TinyORM supports multi-threading for the MSVC and GCC on Linux compilers. Multi-threading is disabled for the Clang <14.0.3 compiler on MSYS2, Clang <14.0.4 on Linux and for the GCC compiler on MSYS2. The reason are bugs in the TLS wrapper that is generated by the thread_local keyword.

A connection can only be used from within the thread that created it. Moving connections between threads or creating queries from a different thread where the connection was created is not supported.

In addition, the third party libraries used by the QSqlDrivers can impose further restrictions on using the SQL Module in a multithreaded program.

In short, if you create a DB::connection in some thread then you have to use this connection only from this particular thread and of course all queries that will be executed on this connection.

If you want to execute some query from another thread for the same connection then you have to create a new connection first and if you have a new connection you can send a query from this new thread to the database.

caution

The schema builder and migrations don't support multi-threading.

- + \ No newline at end of file diff --git a/database/migrations.html b/database/migrations.html index fda921b46..c04f6be30 100644 --- a/database/migrations.html +++ b/database/migrations.html @@ -14,7 +14,7 @@ - + @@ -83,7 +83,7 @@ unsignedTinyInteger uuid year

info

Names of Char, Double, Enum, and Float column methods are in the CamelCase format to avoid collisions with C++ keywords.

bigIncrements()

The bigIncrements method creates an auto-incrementing UNSIGNED BIGINT (primary key) equivalent column:

#include <orm/constants.hpp>

table.bigIncrements(Orm::ID);

bigInteger()

The bigInteger method creates a BIGINT equivalent column:

table.bigInteger("votes");

binary()

The binary method creates a BLOB equivalent column:

table.binary("photo");

boolean()

The boolean method creates a BOOLEAN equivalent column:

table.boolean("confirmed");

Char()

The Char method creates a CHAR equivalent column with of a given length:

#include <orm/constants.hpp>

table.Char(Orm::NAME, 100);

date()

The date method creates a DATE equivalent column:

table.date("created_at");

datetime()

The datetime method creates a DATETIME equivalent column with an optional precision (total digits):

table.datetime("created_at", precision = 0);

datetimes()

The datetimes method creates created_at and updated_at DATETIME equivalent columns with an optional precision (total digits):

table.datetimes(precision = 0);

datetimeTz()

The datetimeTz method creates a DATETIME (with timezone) equivalent column with an optional precision (total digits):

#include <orm/constants.hpp>

table.datetimeTz(Orm::CREATED_AT, precision = 0);

decimal()

The decimal method creates a DECIMAL equivalent column with the given precision (total digits) and scale (decimal digits):

table.decimal("amount", precision = 8, scale = 2);

Double()

The Double method creates a DOUBLE equivalent column with the given precision (total digits) and scale (decimal digits):

table.Double("amount", 8, 2);

Enum()

The Enum method creates a ENUM equivalent column with the given valid values:

table.Enum("difficulty", {"easy", "hard"});

Float()

The Float method creates a FLOAT equivalent column with the given precision (total digits) and scale (decimal digits):

table.Float("amount", 8, 2);

foreignId()

The foreignId method creates an UNSIGNED BIGINT equivalent column:

table.foreignId("user_id");

foreignIdFor()

The foreignIdFor method adds a {column}_id UNSIGNED BIGINT equivalent column for a given model class:

#include "models/user.hpp"

Models::User user;

table.foreignIdFor(User);

foreignUuid()

The foreignUuid method creates a UUID equivalent column:

table.foreignUuid("user_id");

geometry()

The geometry method creates a GEOMETRY equivalent column:

table.geometry("positions");

geometryCollection()

The geometryCollection method creates a GEOMETRYCOLLECTION equivalent column:

table.geometryCollection("positions");

id()

The id method is an alias of the bigIncrements method. By default, the method will create an id column; however, you may pass a column name if you would like to assign a different name to the column:

table.id();

increments()

The increments method creates an auto-incrementing UNSIGNED INTEGER equivalent column as a primary key:

table.increments("id");

integer()

The integer method creates an INTEGER equivalent column:

table.integer("votes");

ipAddress()

The ipAddress method creates a VARCHAR(45) equivalent column:

table.ipAddress("visitor");

json()

The json method creates a JSON equivalent column:

table.json("options");

jsonb()

The jsonb method creates a JSONB equivalent column:

table.jsonb("options");

lineString()

The lineString method creates a LINESTRING equivalent column:

table.lineString("positions");

longBinary()

The longBinary method creates a LONGBLOB equivalent column:

table.longBinary("photo");

longText()

The longText method creates a LONGTEXT equivalent column:

table.longText("description");

macAddress()

The macAddress method creates a column that is intended to hold a MAC address. Some database systems, such as PostgreSQL, have a dedicated column type for this type of data. Other database systems will use a string equivalent VARCHAR(17) column:

table.macAddress("device");

mediumBinary()

The mediumBinary method creates a MEDIUMBLOB equivalent column:

table.mediumBinary("photo");

mediumIncrements()

The mediumIncrements method creates an auto-incrementing UNSIGNED MEDIUMINT equivalent column as a primary key:

table.mediumIncrements("id");

mediumInteger()

The mediumInteger method creates a MEDIUMINT equivalent column:

table.mediumInteger("votes");

mediumText()

The mediumText method creates a MEDIUMTEXT equivalent column:

table.mediumText("description");

multiLineString()

The multiLineString method creates a MULTILINESTRING equivalent column:

table.multiLineString("positions");

multiPoint()

The multiPoint method creates a MULTIPOINT equivalent column:

table.multiPoint("positions");

multiPolygon()

The multiPolygon method creates a MULTIPOLYGON equivalent column:

table.multiPolygon("positions");

point()

The point method creates a POINT equivalent column:

table.point("position");

polygon()

The polygon method creates a POLYGON equivalent column:

table.polygon("position");

rememberToken()

The rememberToken method creates a nullable, VARCHAR(100) equivalent column that is intended to store the current "remember me" authentication token:

table.rememberToken();

set()

The set method creates a SET equivalent column with the given list of valid values:

table.set("flavors", {"strawberry", "vanilla"});

smallIncrements()

The smallIncrements method creates an auto-incrementing UNSIGNED SMALLINT equivalent column as a primary key:

table.smallIncrements("id");

smallInteger()

The smallInteger method creates a SMALLINT equivalent column:

table.smallInteger("votes");

softDeletes()

The softDeletes method adds a nullable deleted_at TIMESTAMP equivalent column with an optional precision (total digits). This column is intended to store the deleted_at timestamp needed for TinyORM's "soft delete" functionality:

table.softDeletes("deleted_at", precision = 0);

softDeletesDatetime()

The softDeletesDatetime method adds a nullable deleted_at DATETIME equivalent column with an optional precision (total digits). This column is intended to store the deleted_at timestamp needed for TinyORM's "soft delete" functionality:

table.softDeletesDatetime("deleted_at", precision = 0);

softDeletesTz()

The softDeletesTz method adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column with an optional precision (total digits). This column is intended to store the deleted_at timestamp needed for TinyORM's "soft delete" functionality:

table.softDeletesTz("deleted_at", precision = 0);

string()

The string method creates a VARCHAR equivalent column of the given length:

#include <orm/constants.hpp>

table.string(Orm::NAME, 100);

text()

The text method creates a TEXT equivalent column:

table.text("description");

time()

The time method creates a TIME equivalent column with an optional precision (total digits):

table.time("sunrise", precision = 0);

timeTz()

The timeTz method creates a TIME (with timezone) equivalent column with an optional precision (total digits):

table.timeTz("sunrise", precision = 0);

timestamp()

The timestamp method creates a TIMESTAMP equivalent column with an optional precision (total digits):

table.timestamp("added_at", precision = 0);

timestampTz()

The timestampTz method creates a TIMESTAMP (with timezone) equivalent column with an optional precision (total digits):

table.timestampTz("added_at", precision = 0);

timestampsTz()

The timestampsTz method creates created_at and updated_at TIMESTAMP (with timezone) equivalent columns with an optional precision (total digits):

table.timestampsTz(precision = 0);

timestamps()

The timestamps method creates created_at and updated_at TIMESTAMP equivalent columns with an optional precision (total digits):

table.timestamps(precision = 0);

tinyBinary()

The tinyBinary method creates a TINYBLOB equivalent column:

table.tinyBinary("photo");

tinyIncrements()

The tinyIncrements method creates an auto-incrementing UNSIGNED TINYINT equivalent column as a primary key:

table.tinyIncrements("id");

tinyInteger()

The tinyInteger method creates a TINYINT equivalent column:

table.tinyInteger("votes");

tinyText()

The tinyText method creates a TINYTEXT equivalent column:

table.tinyText("notes");

unsignedBigInteger()

The unsignedBigInteger method creates an UNSIGNED BIGINT equivalent column:

table.unsignedBigInteger("votes");

unsignedDecimal()

The unsignedDecimal method creates an UNSIGNED DECIMAL equivalent column with an optional precision (total digits) and scale (decimal digits):

table.unsignedDecimal("amount", precision = 8, scale = 2);

unsignedInteger()

The unsignedInteger method creates an UNSIGNED INTEGER equivalent column:

table.unsignedInteger("votes");

unsignedMediumInteger()

The unsignedMediumInteger method creates an UNSIGNED MEDIUMINT equivalent column:

table.unsignedMediumInteger("votes");

unsignedSmallInteger()

The unsignedSmallInteger method creates an UNSIGNED SMALLINT equivalent column:

table.unsignedSmallInteger("votes");

unsignedTinyInteger()

The unsignedTinyInteger method creates an UNSIGNED TINYINT equivalent column:

table.unsignedTinyInteger("votes");

uuid()

The uuid method creates a UUID equivalent column:

table.uuid("id");

year()

The year method creates a YEAR equivalent column:

table.year("birth_year");

Column Modifiers

In addition to the column types listed above, there are several column "modifiers" you may use when adding a column to a database table. For example, to make the column "nullable", you may use the nullable method:

#include <orm/schema.hpp>

Schema::table("users", [](Blueprint &table)
{
table.string("email").nullable();
});

The following table contains all of the available column modifiers. This list does not include index modifiers:

ModifierDescription
.after("column")Place the column "after" another column (MySQL).
.autoIncrement()Set INTEGER columns as auto-incrementing (primary key).
.charset("utf8mb4")Specify a character set for the column (MySQL).
.collation("utf8mb4_unicode_ci")Specify a collation for the column (MySQL/PostgreSQL/SQL Server).
.comment("my comment")Add a comment to a column (MySQL / PostgreSQL).
Special characters are escaped.
.defaultValue(value)Specify a "default" value for the column.
Special characters are escaped.
.first()Place the column "first" in the table (MySQL).
.from(integer)Set the starting value of an auto-incrementing field, an alias for startingValue() (MySQL / PostgreSQL).
.invisible()Make the column "invisible" to SELECT * queries (MySQL).
.nullable(value = true)Allow NULL values to be inserted into the column.
.startingValue(integer)Set the starting value of an auto-incrementing field (MySQL / PostgreSQL).
.storedAs(expression)Create a stored generated column (MySQL / PostgreSQL).
.unsigned()Set INTEGER columns as UNSIGNED (MySQL).
.useCurrent()Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value.
.useCurrentOnUpdate()Set TIMESTAMP columns to use CURRENT_TIMESTAMP when a record is updated.
.virtualAs(expression)Create a virtual generated column (MySQL).
.generatedAs(expression)Create an identity column with specified sequence options (PostgreSQL).
.always()Defines the precedence of sequence values over input for an identity column (PostgreSQL).
.isGeometry()Set spatial column type to geometry - the default type is geography (PostgreSQL).

Default Expressions

The defaultValue modifier accepts a value or an Orm::Query::Expression instance. Using an Expression instance will prevent TinyORM from wrapping the value in quotes and allow you to use database-specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns:

#include <orm/schema.hpp>

using Orm::Query::Expression;

Schema::create("flights", [](Blueprint &table)
{
table.id();
table.json("detail").defaultValue(Expression("(JSON_ARRAY('none'))"));
table.timestamps();
});
note

Support for default expressions depends on your database driver, database version, and the field type. Please refer to your database's documentation.

tip

You can obtain an Orm::Query::Expression using the DB::raw method if you have access to the DB facade.

Column Order

When using the MySQL database, the after method may be used to add columns after an existing column in the schema:

table.after("password", [](Blueprint &table)
{
table.string("address_line1");
table.string("address_line2");
table.string("city");
});

Modifying Columns

The change method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a string column. To see the change method in action, let's increase the size of the name column from 25 to 50. To accomplish this, we simply define the new state of the column and then call the change method:

#include <orm/schema.hpp>

Schema::table("users", [](Blueprint &table)
{
table.string("name", 50).change();
});

When modifying a column, you must explicitly include all of the modifiers you want to keep on the column definition - any missing attribute will be dropped. For example, to retain the unsigned, default, and comment attributes, you must call each modifier explicitly when changing the column:

Schema::table("users", [](Blueprint &table)
{
table.integer("votes").isUnsigned().defaultValue(1).comment("my comment").change();
});
info

The change method and modifying columns is not implemented for the SQLite database because it doesn't support modifying columns out of the box.

Renaming Columns

To rename a column, you may use the renameColumn method provided by the schema builder blueprint:

Schema::table("users", [](Blueprint &table)
{
table.renameColumn("from", "to");
});

Renaming Columns On Legacy Databases

Renaming columns is not supported if you are running a database installation older than one of the following releases:

  • MySQL <8.0.3
  • MariaDB <10.5.2
  • SQLite <3.25.0

Dropping Columns

To drop a column, you may use the dropColumn method on the schema builder blueprint:

Schema::table("users", [](Blueprint &table)
{
table.dropColumn("votes");
});

You may drop multiple columns from a table by passing a QVector<QString> of column names to the dropColumns method, the dropColumns method also provides parameter pack overload:

Schema::table("users", [](Blueprint &table)
{
table.dropColumns({"votes", "avatar", "location"});
// Parameter pack overload
table.dropColumns("votes", "avatar", "location");
});
caution

The SQLite prior to v3.35.0 doesn't support dropping columns using the ALTER TABLE DROP COLUMN, dropping columns was added in the SQLite v3.35.0 as is described in the release notes.

Available Command Aliases

TinyORM provides several convenient methods related to dropping common types of columns. Each of these methods is described in the table below:

CommandDescription
table.dropRememberToken();Drop the remember_token column.
table.dropSoftDeletes();Drop the deleted_at column.
table.dropSoftDeletesDatetime();Alias of dropSoftDeletes() method.
table.dropSoftDeletesTz();Alias of dropSoftDeletes() method.
table.dropTimestamps();Drop the created_at and updated_at columns.
table.dropTimestampsTz();Alias of dropTimestamps() method.
table.dropDatetimes();Alias of dropTimestamps() method.

Indexes

Creating Indexes

The TinyORM schema builder supports several types of indexes. The following example creates a new email column and specifies that its values should be unique. To create the index, we can chain the unique method onto the column definition:

#include <orm/schema.hpp>

Schema::table("users", [](Blueprint &table)
{
table.string("email").unique();
});

Alternatively, you may create the index after defining the column. To do so, you should call the unique method on the schema builder blueprint. This method accepts the name of the column that should receive a unique index:

table.unique("email");

You may even pass a QVector<QString> of columns to an index method to create a compound (or composite) index:

table.index({"account_id", "created_at"});

When creating an index, TinyORM will automatically generate an index name based on the table, column names, and the index type (eg. users_email_unique), but you may pass a second argument to the method to specify the index name yourself:

table.unique("email", "unique_email");

Available Index Types

TinyORM's schema builder blueprint class provides methods for creating each type of index supported by TinyORM. Each index method accepts an optional second argument to specify the name of the index. If omitted, the name will be derived from the names of the table and column(s) used for the index, as well as the index type (eg. users_email_fulltext). Each of the available index methods is described in the table below:

CommandDescription
table.primary("id");Adds a primary key.
table.primary({"id", "parent_id"});Adds composite keys.
table.unique("email");Adds a unique index.
table.index("state");Adds an index.
table.fullText("body");Adds a full text index (MySQL/PostgreSQL).
table.fullText("body").language("english");Adds a full text index of the specified language (PostgreSQL).
table.spatialIndex("location");Adds a spatial index (except SQLite).

Index Lengths & MySQL / MariaDB

By default, TinyORM uses the utf8mb4 character set. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure the default string length by calling the Schema::defaultStringLength method:

#include <orm/schema.hpp>

Schema::defaultStringLength(191);
tip

Alternatively, you may enable the innodb_large_prefix option for your database (enabled by default in >=MySQL 5.7.7). Refer to your database's documentation for instructions on how to properly enable this option.

Renaming Indexes

To rename an index, you may use the renameIndex method provided by the schema builder blueprint. This method accepts the current index name as its first argument and the desired name as its second argument:

table.renameIndex("from", "to");

Dropping Indexes

To drop an index, you must specify the index's name. By default, TinyORM automatically assigns an index name based on the table name, the name of the indexed column, and the index type (eg. users_email_unique). Here are some examples:

CommandDescription
table.dropPrimary("users_id_primary");Drop a primary key from the "users" table.
table.dropUnique("users_email_unique");Drop a unique index from the "users" table.
table.dropIndex("geo_state_index");Drop a basic index from the "geo" table.
table.dropFullText("posts_body_fulltext");Drop a full text index from the "posts" table.
.dropSpatialIndex("geo_location_spatialindex");Drop a spatial index from the "geo" table (except SQLite).

I may also drop indexes by a column name or column names for composite keys, if you pass a QVector<QString> of columns into a method that drops indexes, the conventional index name will be generated based on the table name, columns, and index type:

Schema::table("geo", [](Blueprint &table)
{
table.dropIndex({"state"}); // Drops index 'geo_state_index'
});

Foreign Key Constraints

TinyORM also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:

#include <orm/schema.hpp>

using Orm::Constants::ID;

Schema::table("posts", [](Blueprint &table)
{
table.unsignedBigInteger("user_id");

table.foreign("user_id").references(ID).on("users");
});

Since this syntax is rather verbose, TinyORM provides additional, terser methods that use conventions to provide a better developer experience. When using the foreignId method to create your column, the example above can be rewritten like so:

Schema::table("posts", [](Blueprint &table)
{
table.foreignId("user_id").constrained();
});

The foreignId method creates an UNSIGNED BIGINT equivalent column, while the constrained method will use conventions to determine the table and column name being referenced. If your table name does not match TinyORM's conventions, you may specify the table name by passing it as an argument to the constrained method:

Schema::table("posts", [](Blueprint &table)
{
table.foreignId("user_id").constrained("users");
});

You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

#include <orm/constants.hpp>

using Orm::SchemaNs::Constants::Cascade;

table.foreignId("user_id")
.constrained()
.onUpdate("cascade")
.onDelete(Cascade);

An alternative, expressive syntax is also provided for these actions:

MethodDescription
table.cascadeOnUpdate();Updates should cascade.
table.restrictOnUpdate();Updates should be restricted.
table.cascadeOnDelete();Deletes should cascade.
table.restrictOnDelete();Deletes should be restricted.
table.nullOnDelete();Deletes should set the foreign key value to null.

Any additional column modifiers must be called before the constrained method:

table.foreignId("user_id")
.nullable()
.constrained();

Dropping Foreign Keys

To drop a foreign key, you may use the dropForeign method, passing the name of the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes. In other words, the foreign key constraint name is based on the name of the table and the columns in the constraint, followed by a "_foreign" suffix:

table.dropForeign("posts_user_id_foreign");

Alternatively, you may pass a QVector<QString> containing the column name that holds the foreign key to the dropForeign method. The QVector will be converted to a foreign key constraint name using TinyORM's constraint naming conventions:

table.dropForeign({"user_id"});

Toggling Foreign Key Constraints

You may enable or disable foreign key constraints within your migrations by using the following methods:

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

Schema::withoutForeignKeyConstraints([]
{
// Constraints disabled within this lambda expression...
});
caution

The SQLite disables foreign key constraints by default. When using SQLite, make sure to enable foreign key support in your database configuration before attempting to create them in your migrations. In addition, SQLite only supports creating foreign keys when creating tables and not when tables are altered.

- + \ No newline at end of file diff --git a/database/query-builder.html b/database/query-builder.html index 55cadaa83..f4c7ea852 100644 --- a/database/query-builder.html +++ b/database/query-builder.html @@ -14,13 +14,13 @@ - +

Database: Query Builder

Introduction

TinyORM's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application.

The TinyORM query builder uses QSqlQuery parameter binding to protect your application against SQL injection attacks. There is no need to clean or sanitize strings passed to the query builder as query bindings.

danger

QSqlQuery does not support binding column names. Therefore, you should never allow user input to dictate the column names referenced by your queries, including "order by" columns.

danger

The QMYSQL Qt driver contains a bug, if your table contains a json column type, then you must explicitly name columns other than json columns instead of the * shorthand, otherwise, you will get an empty result, or all column values will be invalid QVariant-s, or it may even return half of the columns. The QPSQL driver returns correct results and doesn't have problem with json columns. It was fixed in the Qt 5.15.12, 6.2.7, 6.5.0 QTBUG-101680.

Running Database Queries

Retrieving All Rows From A Table

You may use the table method provided by the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally retrieve the results of the query using the get method:

#include <orm/db.hpp>

// Log a list of all of the application's users
auto query = DB::table("users")->get();

while (query.next())
qDebug() << "id :" << query.value("id").toULongLong() << ";"
<< "name :" << query.value("name").toString();

The get method returns a QSqlQuery containing the results of the query where each result can be accessed by QSqlQuery::next method, look into the QSqlQuery documentation how to obtain results from the "query". You may access each column's value by QSqlQuery::value method. The first bool return value is the value returned from QSqlQuery::exec method:

#include <QDebug>

#include <orm/db.hpp>

auto users = DB::table("users")->get();

while(users.next())
qDebug() << users.value("name").toString();

Retrieving A Single Row / Column From A Table

If you just need to retrieve a single row from a database table, you may use the QueryBuilder::first method. This method will return a QSqlQuery object, on which was internally called QSqlQuery::first method. This method retrieves the first record in the result, if available, and positions the query on the retrieved record:

auto user = DB::table("users")->whereEq("name", "John").first();

user.value("email").toString();

If you don't need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly as QVariant:

auto email = DB::table("users")->whereEq("name", "John").value("email").toString();

To retrieve a single row by its id column value, use the find method. This method retrieves the first record in the result, if available, and positions the query on the retrieved record:

auto user = DB::table("users")->find(3);

user.value("email").toString();

Retrieving A List Of Column Values

If you would like to retrieve the QVector<QVariant> instance containing the values of a single column, you may use the pluck method. In this example, we'll retrieve a collection of user titles:

#include <QDebug>

#include <orm/db.hpp>

const auto titles = DB::table("users")->pluck("title");

for (const auto &title : titles)
qDebug() << title.value<QString>();

You may specify the column that the resulting collection should use as its keys by providing a second argument to the pluck method, following example returns the std::map<QString, QVariant> of "titles" keyed by "names":

#include <orm/db.hpp>

auto titles = DB::table("users")->pluck<QString>("title", "name");

for (auto &&[name, title] : titles)
qDebug() << name << ":" << title.value<QString>();

You may also use pluck<quint64>("name", "id"), it returns the std::map<quint64, QVariant> of "names" keyed by its "ids".

note

This second pluck overload returns std::map<T, QVariant> so you have to provide a template argument for the key type.

Concatenate column values

The implode method can be used to join column values. For example, you may use this method to concatenate prices with the , character as the glue:

DB::table("orders")->where("price", ">", 100).implode("price", ", ");

Chunking Results

If you need to work with thousands of database records, consider using the chunk method provided by the DB facade. This method retrieves a small chunk of results at a time and feeds each chunk into a lambda expression for processing. For example, let's retrieve the entire users table in chunks of 100 records at a time:

DB::table("users")->orderBy("id").chunk(100, [](QSqlQuery &users, const int page)
{
while (users.next()) {
//
}

return true;
});

You may stop further chunks from being processed by returning false from the closure:

DB::table("users")->orderBy("id").chunk(100, [](QSqlQuery &users, const int page)
{
// Process the records...

return false;
});

If you are updating database records while chunking results, your chunk results could change in unexpected ways. If you plan to update the retrieved records while chunking, it is always best to use the chunkById method instead. This method will automatically paginate the results based on the record's primary key:

DB::table("users")
->whereEq("active", false)
.orderBy("id")
.chunkById(100, [](QSqlQuery &users, const int /*unused*/)
{
while (users.next())
DB::table("users")
->whereEq("id", users.value("id"))
.update({{"active", true}});

return true;
});
caution

When updating or deleting records inside the chunk lambda expression, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the chunked results, it can be avoided using the chunkById method.

Aggregates

The query builder also provides a variety of methods for retrieving aggregate values like count, max, min, avg, and sum. You may call any of these methods after constructing your query:

#include <orm/db.hpp>

auto users = DB::table("users")->count();

auto price = DB::table("orders")->max("price");

Of course, you may combine these methods with other clauses to fine-tune how your aggregate value is calculated:

auto price = DB::table("orders")
->whereEq("finalized", 1)
.avg("price");

Determining If Records Exist

Instead of using the count method to determine if any records exist that match your query's constraints, you may use the exists and doesntExist methods:

if (DB::table("orders")->whereEq("finalized", 1).exists()) {
// ...
}

if (DB::table("orders")->whereEq("finalized", 1).doesntExist()) {
// ...
}

Select Statements

Specifying A Select Clause

You may not always want to select all columns from a database table. Using the select method, you can specify a custom "select" clause for the query:

#include <orm/db.hpp>

auto users = DB::table("users")
->select({"name", "email as user_email"})
.get();

The distinct method allows you to force the query to return distinct results:

auto users = DB::table("users")->distinct().get();

If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:

auto query = DB::table("users")->select("name");

auto users = query.addSelect("age").get();
note

You can also pass subqueries to the select and addSelect methods. A subquery can be a lambda expression, raw string, or the QueryBuilder instance.

Raw Expressions

Sometimes you may need to insert an arbitrary string into a query. To create a raw string expression, you may use the raw method provided by the DB facade:

auto users = DB::table("users")
->select(DB::raw("count(*) as user_count, status"))
.where("status", "<>", 1)
.groupBy("status")
.get();
danger

Raw statements will be injected into the query as strings, so you should be extremely careful to avoid creating SQL injection vulnerabilities.

Raw Methods

Instead of using the DB::raw method, you may also use the following methods to insert a raw expression into various parts of your query. Remember, TinyORM can not guarantee that any query using raw expressions is protected against SQL injection vulnerabilities.

selectRaw

The selectRaw method can be used in place of addSelect(DB::raw(...)). This method accepts an optional vector of bindings as its second argument:

auto orders = DB::table("orders")
->selectRaw("price * ? as price_with_tax", {1.0825})
.get();

fromRaw

The fromRaw method may be used to provide a raw string as the value of the "from" clause:

auto users = DB::connection("postgres").query()
->fromRaw("(select id, name from users where id < ?) as u", {5})
.where("id", "<", 3)
.get();

whereRaw / orWhereRaw

The whereRaw and orWhereRaw methods can be used to inject a raw "where" clause into your query. These methods accept an optional vector of bindings as their second argument:

auto orders = DB::table("orders")
->whereRaw("price > IF(state = \"TX\", ?, 100)", {200})
.get();

groupByRaw

The groupByRaw method may be used to provide a raw string as the value of the group by clause:

auto orders = DB::table("orders")
->select({"city", "state"})
.groupByRaw("city, state")
.get();

havingRaw / orHavingRaw

The havingRaw and orHavingRaw methods may be used to provide a raw string as the value of the "having" clause. These methods accept an optional vector of bindings as their second argument:

auto orders = DB::table("orders")
->select({"department", DB::raw("SUM(price) as total_sales")})
.groupBy("department")
.havingRaw("SUM(price) > ?", {2500})
.get();

orderByRaw

The orderByRaw method may be used to provide a raw string as the value of the "order by" clause:

auto orders = DB::table("orders")
->orderByRaw("updated_at - created_at DESC")
.get();

Joins

Inner Join Clause

The query builder may also be used to add join clauses to your queries. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. You may even join multiple tables in a single query:

#include <orm/db.hpp>

auto users = DB::table("users")
->join("contacts", "users.id", "=", "contacts.user_id")
.join("orders", "users.id", "=", "orders.user_id")
.select({"users.*", "contacts.phone", "orders.price"})
.get();

Left Join / Right Join Clause

If you would like to perform a "left join" or "right join" instead of an "inner join", use the leftJoin or rightJoin methods. These methods have the same signature as the join method:

auto users = DB::table("users")
->leftJoin("posts", "users.id", "=", "posts.user_id")
.get();

auto users = DB::table("users")
->rightJoin("posts", "users.id", "=", "posts.user_id")
.get();

Cross Join Clause

You may use the crossJoin method to perform a "cross join". Cross joins generate a cartesian product between the first table and the joined table:

auto sizes = DB::table("sizes")
->crossJoin("colors")
.get();

Advanced Join Clauses

You may also specify more advanced join clauses. To get started, pass a lambda expression as the second argument to the join method. The lambda expression will receive a Orm::Query::JoinClause instance which allows you to specify constraints on the "join" clause:

#include <orm/db.hpp>
#include <orm/query/joinclause.hpp>

DB::table("users")
->join("contacts", [](auto &join)
{
join.on("users.id", "=", "contacts.user_id")
.orOn(...);
})
.get();

If you would like to use a "where" clause on your joins, you may use the where and orWhere methods provided by the Orm::Query::JoinClause instance. Instead of comparing two columns, these methods will compare the column against a value:

DB::table("users")
->join("contacts", [](auto &join)
{
join.on("users.id", "=", "contacts.user_id")
.where("contacts.user_id", ">", 5);
})
.get();

Subquery Joins

You may use the joinSub, leftJoinSub, and rightJoinSub methods to join a query to a subquery. Each of these methods receives three arguments: the subquery, its table alias, and a lambda expression that defines the related columns. In this example, we will retrieve a collection of users where each user record also contains the created_at timestamp of the user's most recently published blog post:

auto latestPosts = DB::table("posts")
->select({"user_id", DB::raw("MAX(created_at) as last_post_created_at")})
.whereEq("is_published", true)
.groupBy("user_id");

auto users = DB::table("users")
->joinSub(latestPosts, "latest_posts", [](auto &join)
{
join.on("users.id", "=", "latest_posts.user_id");
}).get();

Basic Where Clauses

Where Clauses

You may use the query builder's where method to add "where" clauses to the query. The most basic call to the where method requires three arguments. The first argument is the name of the column. The second argument is an operator, which can be any of the database's supported operators. The third argument is the value to compare against the column's value.

For example, the following query retrieves users where the value of the votes column is equal to 100 and the value of the age column is greater than 35:

auto users = DB::table("users")
->where("votes", "=", 100)
.where("age", ">", 35)
.get();

For convenience, if you want to verify that a column is = to a given value, you may call whereEq method. Similar XxxEq methods are also defined for other commands:

auto users = DB::table("users")->whereEq("votes", 100).get();

As previously mentioned, you may use any operator that is supported by your database system:

auto users = DB::table("users")
->where("votes", ">=", 100)
.get();

auto users = DB::table("users")
->where("votes", "<>", 100)
.get();

auto users = DB::table("users")
->where("name", "like", "T%")
.get();

You may also pass a QVector<Orm::WhereItem> of conditions to the where function. Each Orm::WhereItem structure should contain the four arguments typically passed to the where method:

auto users = DB::table("users")
->where({
{"status", 1}, // "=" by default
{"subscribed", 1, "<>"},
}).get();

Or Where Clauses

When chaining together calls to the query builder's where method, the "where" clauses will be joined together using the and operator. However, you may use the orWhere or orWhereEq method to join a clause to the query using the or operator. The orWhere method accepts the same arguments as the where method:

auto users = DB::table("users")
->where("votes", ">", 100)
.orWhere("name", "=", "John")
.orWhereEq("name", "Jack")
.get();

If you need to group an "or" condition within parentheses, you may pass a lambda expression as the first argument to the orWhere method:

auto users = DB::table("users")
->where("votes", ">", 100)
.orWhere([](auto &query)
{
query.whereEq("name", "Abigail")
.where("votes", ">", 50);
})
.get();

The example above will produce the following SQL:

select * from users where votes > 100 or (name = "Abigail" and votes > 50)

Condition Operator Overriding

The where method overload with a QVector<Orm::WhereItem> as the first argument joins conditions using the and operator by default:

auto users = DB::table("users")
->where({
{"first_name", "John"},
{"votes", 50, ">"},
}).get();

Conditions operator can be overridden by the fourth argument in the Orm::WhereItem structure:

auto users = DB::table("users")
->where({
{"first_name", "John"},
{"votes", 50, ">", "or"},
}).get();

Or by the second where argument, in this case all conditions will be joined by this condition, but it is still possible to override them by the fourth argument in the Orm::WhereItem structure:

auto users = DB::table("users")
->where({
{"first_name", "John"},
{"last_name", "Smith"},
{"votes", 50, ">", "and"},
}, "or")
.get();

The example above will produce the following SQL:

select * from users where (first_name = "John" or last_name = "Smith" and votes > 50)
tip

Still, it is a better idea to use Logical Grouping described few lines below, which allows better control of the parentheses.

Where Not Clauses

The whereNot and orWhereNot methods may be used to negate a given group of query constraints. For example, the following query excludes products that are on clearance or which have a price that is less than ten:

auto products = DB::table("products")
->whereNot([](auto &query) {
query.whereEq("clearance", true)
.orWhere("price", "<", 10);
})
.get();

Additional Where Clauses

whereBetween / orWhereBetween

The whereBetween method verifies that a column's value is between two values:

auto users = DB::table("users")
->whereBetween("votes", {1, 100})
.get();

whereNotBetween / orWhereNotBetween

The whereNotBetween method verifies that a column's value lies outside of two values:

auto users = DB::table("users")
->whereNotBetween("votes", {1, 100})
.get();

whereBetweenColumns / orWhereBetweenColumns

The whereBetweenColumns method verifies that a column's value is between two values in given columns:

auto files = DB::table("files")
->whereBetweenColumns("quota", {"min_allowed_quota", "max_allowed_quota"})
.get();

whereNotBetweenColumns / orWhereNotBetweenColumns

The whereNotBetweenColumns method verifies that a column's value lies outside of two values in given columns:

auto files = DB::table("files")
->whereNotBetweenColumns("quota", {"min_allowed_quota", "max_allowed_quota"})
.get();

whereIn / whereNotIn / orWhereIn / orWhereNotIn

The whereIn method verifies that a given column's value is contained within the given QVector<QVariant>:

auto users = DB::table("users")
->whereIn("id", {1, 2, 3})
.get();

The whereNotIn method verifies that the given column's value is not contained in the given QVector<QVariant>:

auto users = DB::table("users")
->whereNotIn("id", {1, 2, 3})
.get();

whereNull / whereNotNull / orWhereNull / orWhereNotNull

The whereNull method verifies that the value of the given column is NULL:

auto users = DB::table("users")
->whereNull("updated_at")
.get();

The whereNotNull method verifies that the column's value is not NULL:

auto users = DB::table("users")
->whereNotNull("updated_at")
.get();

whereDate / whereTime / whereDay / whereMonth / whereYear

The whereDate method may be used to compare a column's value against a date:

auto users = DB::table("users")
->whereDate("created_at", EQ, QDate(2022, 11, 18))
.get();

The whereTime method may be used to compare a column's value against a specific time:

auto users = DB::table("users")
->whereTime("created_at", "=", QTime(11, 14, 23))
.get();

The whereDay method may be used to compare a column's value against a specific day of the month:

auto users = DB::table("users")
->whereDay("created_at", "<=", 15)
.get();

The whereMonth method may be used to compare a column's value against a specific month:

auto users = DB::table("users")
->whereEqMonth("created_at", 12)
.get();

The whereYear method may be used to compare a column's value against a specific year:

auto users = DB::table("users")
->whereEqYear("created_at", 2016)
.get();

The whereDate and whereTime methods also accept a QDateTime instance or you can pass values as a QString in 2022-12-31 or 09:15:11 formats.

The whereDay, whereMoth, and whereYear accept QDate or QDateTime instances, an integral number or a QString that contains an integral number.

info

All the above methods offer whereEqXyz and orWhereXyz shortcut methods.

whereColumn / orWhereColumn

The whereColumnEq method may be used to verify that two columns are equal:

auto users = DB::table("users")
->whereColumnEq("first_name", "last_name")
.get();

You may also pass a comparison operator to the whereColumn method:

auto users = DB::table("users")
->whereColumn("updated_at", ">", "created_at")
.get();

You may also pass a QVector<Orm::WhereColumnItem> of column comparisons to the whereColumn method. These conditions will be joined using the and operator:

auto users = DB::table("users")
->whereColumn({
{"first_name", "last_name"},
{"updated_at", "created_at", ">"},
}).get();

Conditions operator can also be overridden by the fourth argument in the Orm::WhereColumnItem structure:

auto users = DB::table("users")
->whereColumn({
{"first_name", "last_name"},
{"updated_at", "created_at", ">", "or"},
}).get();

Or by the second whereColumn argument:

auto users = DB::table("users")
->whereColumn({
{"first_name", "last_name"},
{"updated_at", "created_at", ">"},
}, "or")
.get();

Logical Grouping

Sometimes you may need to group several "where" clauses within parentheses in order to achieve your query's desired logical grouping. In fact, you should generally always group calls to the orWhere method in parentheses in order to avoid unexpected query behavior. To accomplish this, you may pass a lambda expression to the where method:

auto users = DB::table("users")
->where("name", "=", "John")
.where([](auto &query)
{
query.where("votes", ">", 100)
.orWhere("title", "=", "Admin");
})
.get();

As you can see, passing a lambda expression into the where method instructs the query builder to begin a constraint group. The lambda expression will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group. The example above will produce the following SQL:

select * from users where name = "John" and (votes > 100 or title = "Admin")

Advanced Where Clauses

Where Exists Clauses

The whereExists method allows you to write "where exists" SQL clauses. The whereExists method accepts a lambda expression which will receive a query builder instance, allowing you to define the query that should be placed inside of the "exists" clause:

auto users = DB::table("users")
->whereExists([](auto &query)
{
query.select(DB::raw(1))
.from("orders")
.whereColumnEq("orders.user_id", "users.id");
})
.get();

Alternatively, you may provide a query object to the whereExists method instead of a lambda expression:

// Ownership of the std::shared_ptr<QueryBuilder>
auto builder = DB::table("orders");
auto orders = builder->select(DB::raw(1))
.whereColumnEq("orders.user_id", "users.id");

auto users = DB::table("users")
->whereExists(orders)
.get();

Or directly:

auto users = DB::table("users")
->whereExists(DB::table("orders")
->select(DB::raw(1))
.whereColumnEq("orders.user_id", "users.id"))
.get();

All of the examples above will produce the following SQL:

select * from users
where exists (
select 1
from orders
where orders.user_id = users.id
)

Subquery Where Clauses

Sometimes you may need to construct a "where" clause that compares the results of a subquery to a given value. You may accomplish this by passing a lambda expression and a value to the where method. For example, the following query will retrieve all users who have a recent "membership" of a given type:

#include "models/user.hpp"

auto users = User::whereEq([](auto &query)
{
query.select("type")
.from("membership")
.whereColumnEq("membership.user_id", "users.id")
.orderByDesc("membership.start_date")
.limit(1);
}, "Pro")->get();

Or, you may need to construct a "where" clause that compares a column to the results of a subquery. You may accomplish this by passing a column, operator, and lambda expression to the where method. For example, the following query will retrieve all income records where the amount is less than average;

#include "models/income.hpp"

auto incomes = Income::where("amount", "<", [](auto &query)
{
query.selectRaw("avg(i.amount)").from("incomes as i");
})->get();

Ordering, Grouping, Limit & Offset

Ordering

The orderBy Method

The orderBy method allows you to sort the results of the query by a given column. The first argument accepted by the orderBy method should be the column you wish to sort by, while the second argument determines the direction of the sort and may be either asc or desc:

auto users = DB::table("users")
->orderBy("name", "desc")
.get();

To sort by multiple columns, you may simply invoke orderBy as many times as necessary:

auto users = DB::table("users")
->orderBy("name", "desc")
.orderBy("email", "asc")
.get();

The latest & oldest Methods

The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the table's created_at column. Or, you may pass the column name that you wish to sort by:

auto user = DB::table("users")
->latest()
.first();

Random Ordering

The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

auto randomUser = DB::table("users")
->inRandomOrder()
.first();

Removing Existing Orderings

The reorder method removes all of the "order by" clauses that have previously been applied to the query:

auto &query = DB::table("users")->orderBy("name");

auto unorderedUsers = query.reorder().get();

You may pass a column and direction when calling the reorder method in order to remove all existing "order by" clauses and apply an entirely new order to the query:

auto &query = DB::table("users")->orderBy("name");

auto usersOrderedByEmail = query.reorder("email", "desc").get();

Grouping

The groupBy & having Methods

As you might expect, the groupBy and having methods may be used to group the query results. The having method's signature is similar to that of the where method:

auto users = DB::table("users")
->groupBy("account_id")
.having("account_id", ">", 100)
.get();

You may pass multiple items to the groupBy method to group by multiple columns:

auto users = DB::table("users")
->groupBy({"first_name", "status"})
.having("account_id", ">", 100)
.get();

Limit & Offset

The skip & take Methods

You may use the skip and take methods to limit the number of results returned from the query or to skip a given number of results in the query:

auto users = DB::table("users")->skip(10).take(5).get();

Alternatively, you may use the limit and offset methods. These methods are functionally equivalent to the take and skip methods, respectively:

auto users = DB::table("users")
->offset(10)
.limit(5)
.get();

Insert Statements

The query builder also provides an insert method that may be used to insert records into the database table. The insert method accepts the QVariantMap of column names and values:

DB::table("users")->insert({
{"email", "kayla@example.com"},
{"votes", 0},
});

You may insert several records at once by passing a QVector<QString> for column names as the first argument and QVector<QVector<QVariant>> for values as the second argument. Each QVector<QVariant> represents a record that should be inserted into the table. This overload is useful for multi-insert and allows to specify column names only once:

DB::table("users")->insert({"email", "votes"},
{
{"picard@example.com", 0},
{"janeway@example.com", 0},
});

You may also insert several records at once by passing a QVector<QVariantMap>. Each QVariantMap represents a record that should be inserted into the table:

DB::table("users")->insert({
{{"email", "picard@example.com"}, {"votes", 0}},
{{"email", "janeway@example.com"}, {"votes", 0}},
});

The insertOrIgnore method will ignore duplicate record errors while inserting records into the database and also provides the same overloads like the insert method. When using this method, you should be aware that duplicate record errors will be ignored and other types of errors may also be ignored depending on the database engine. For example, insertOrIgnore will bypass MySQL's strict mode:

DB::table("users")->insertOrIgnore({"id", "email"},
{
{1, "sisko@example.com"},
{2, "archer@example.com"},
});

DB::table("users")->insertOrIgnore({
{{"id", 1}, {"email", "sisko@example.com"}},
{{"id", 2}, {"email", "archer@example.com"}},
});

Auto-Incrementing IDs

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

auto id = DB::table("users")->insertGetId({
{"email", "john@example.com"},
{"votes", 0},
});

Upserts

The upsert method will insert records that do not exist and update the records that already exist with new values that you may specify. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is a vector of columns that should be updated if a matching record already exists in the database:

DB::table("flights")->upsert(
{{{"departure", "Oakland"}, {"destination", "San Diego"}, {"price", 99}},
{{"departure", "Chicago"}, {"destination", "New York"}, {"price", 150}}},
{"departure", "destination"},
{"price"}
);

In the example above, TinyORM will attempt to insert two records. If a record already exists with the same departure and destination column values, TinyORM will update that record's price column.

caution

All databases except SQL Server require the columns in the second argument of the upsert method to have a "primary" or "unique" index. In addition, the MySQL database driver ignores the second argument of the upsert method and always uses the "primary" and "unique" indexes of the table to detect existing records.

info

Row and column aliases will be used with the MySQL server >=8.0.19 instead of the VALUES() function as is described in the MySQL documentation. The MySQL server version is auto-detected and can be overridden in the configuration.

Update Statements

In addition to inserting records into the database, the query builder can also update existing records using the update method. The update method, accepts a QVector<Orm::UpdateItem> of column and value pairs, indicating the columns to be updated and returns a std::tuple<int, QSqlQuery> . You may constrain the update query using where clauses:

auto [affected, query] = DB::table("users")
->whereEq("id", 1)
.update({{"votes", 1}});
note

An update and delete are affecting statements, so they return std::tuple<int, QSqlQuery>.

Update Or Insert

Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: a vector of conditions by which to find the record, and a vector of column and value pairs indicating the columns to be updated.

The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments:

DB::table("users")
->updateOrInsert(
{{"email", "john@example.com"}, {"name", "John"}},
{{"votes", 2}}
);

Increment & Decrement

The query builder also provides convenient methods for incrementing or decrementing the value of a given column. Both of these methods accept at least one argument: the column to modify. A second argument may be provided to specify the amount by which the column should be incremented or decremented:

DB::table("users")->increment<int>("votes");

DB::table("users")->increment("votes", 5);

DB::table("users")->decrement<int>("votes");

DB::table("users")->decrement("votes", 5.2); // float or double type

You may also specify additional columns to update during the operation as a QVector<Orm::UpdateItem>:

DB::table("users")->increment("votes", 1, {{"name", "John"}});

You should constrain increment, decrement by where to update only specific record in the database, otherwise a column in all records will be modified.

DB::table("users")->whereEq("id", 1).increment("votes", 5);

Delete Statements

The query builder's remove, or an alias deleteRow method may be used to delete records from the table. You may constrain delete statements by adding "where" clauses before calling the delete method:

DB::table("users")->remove();

DB::table("users")->where("votes", ">", 100).remove();
note

delete can not be used as the method name because it is the reserved word.

You may also pass record id to the remove method as the first argument, it is the shortcut method, which internally calls where:

DB::table("users")->remove(2);

Truncate Statement

If you wish to truncate an entire table, which will remove all records from the table and reset the auto-incrementing ID to zero, you may use the truncate method:

DB::table("users")->truncate();

Table Truncation & PostgreSQL

When truncating a PostgreSQL database, the CASCADE behavior will be applied. This means that all foreign key related records in other tables will be deleted as well.

Pessimistic Locking

The query builder also includes a few functions to help you achieve "pessimistic locking" when executing your select statements. To execute a statement with a "shared lock", you may call the sharedLock method. A shared lock prevents the selected rows from being modified until your transaction is committed:

DB::table("users")
->where("votes", ">", 100)
.sharedLock()
.get();

Alternatively, you may use the lockForUpdate method. A "for update" lock prevents the selected records from being modified or from being selected with another shared lock:

DB::table("users")
->where("votes", ">", 100)
.lockForUpdate()
.get();

Debugging

You may use the dd and dump methods while building a query to dump the current query bindings and SQL. The dd method will display the debug information and then stop executing using the exit(1). The dump method will display the debug information and continue executing:

DB::table("users")->where("votes", ">", 100).dd();

DB::table("users")->where("votes", ">", 100).dump();
- + \ No newline at end of file diff --git a/database/seeding.html b/database/seeding.html index 9b6859e31..82bff1675 100644 --- a/database/seeding.html +++ b/database/seeding.html @@ -14,13 +14,13 @@ - +

Database: Seeding

Introduction

TinyORM includes the ability to seed your database with data using seed classes. All seed classes should be stored in the database/seeders directory. The DatabaseSeeder class is considered as the root seeder. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

tip

Mass assignment protection is automatically disabled during database seeding.

Writing Seeders

To generate a seeder, execute the make:seeder tom command. A new seeder will be placed in the database/seeders directory relative to the current pwd:

tom make:seeder UserSeeder
tip

You can omit the Seeder word in the class name, tom appends it for you.

A seeder class only contains one method by default: run. This method is called when the db:seed tom command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data.

As an example, let's modify the default DatabaseSeeder class and add a database insert statement to the run method:

#pragma once

#include <tom/seeder.hpp>

namespace Seeders
{

/*! Main database seeder. */
struct DatabaseSeeder : Seeder
{
/*! Run the database seeders. */
void run() override
{
DB::table("users")->insert({"name", "email"},
{
{"1. user", "user1@example.com"},
{"2. user", "user2@example.com"},
});
}
};

} // namespace Seeders
tip

The multi-insert insert method overload is ideal for seeding data.

Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes too large. The call method accepts the template parameter pack of seeder classes that should be executed:

/*! Run the database seeders. */
void run() override
{
call<UserSeeder, PostSeeder, CommentSeeder>();
}

Call with additional arguments

The call method allows to pass additional arguments to the seeder/s, but it has additional requirements.

If you define a run method without parameters then this method is called using the virtual dispatch (polymorphism) and in this case, you should use the override specifier.

If you define your run method eg. like this run(bool shouldSeed) or whatever parameters you want, then this method is called using the fold expression (virtual dispatch is not used in this case) so you can't use the override specifier and you must call the call<>() method with exactly the same arguments like the run method was defined with, in our example, it should look like this call<ExampleSeeder>(true).

Let's demonstrate it on a small example, following is the run method in the root DatabaseSeeder class.

/*! Run the database seeders. */
void run() override
{
// This value can be based eg. on data from the database
const auto shouldSeed = true;

call<UserSeeder>(shouldSeed);
}

The run method in the UserSeeder class.

/*! Run the database seeders. */
void run(const bool shouldSeed)
{
if (!shouldSeed)
return;

DB::table("users")->insert({
{"name", "1. user"},
});
}
tip

The call method provides two shortcut methods, callWith and callSilent (no output from seeders).

Running Seeders

You may execute the db:seed tom command to seed your database. By default, the db:seed command runs the Seeders::DatabaseSeeder class, which may in turn invoke other seed classes. However, you may use the --class option to specify a specific seeder class to run individually:

tom db:seed

tom db:seed --class=UserSeeder

You may also seed your database using the migrate, migrate:fresh or migrate:refresh commands in combination with the --seed option. For example the migrate:fresh command drops all tables and re-run all of your migrations. This command is useful for completely re-building your database:

tom migrate:fresh --seed
tip

You can change the default seeders path as is described in the C preprocessor macros, CMake provides the TOM_SEEDERS_DIR option.

Forcing Seeders To Run In Production

Some seeding operations may cause you to alter or lose data. In order to protect you from running seeding commands against your production database, you will be prompted for confirmation before the seeders are executed in the production environment. To force the seeders to run without a prompt, use the --force flag:

tom db:seed --force
- + \ No newline at end of file diff --git a/dependencies.html b/dependencies.html index aef7b7ab5..6ad761513 100644 --- a/dependencies.html +++ b/dependencies.html @@ -14,14 +14,14 @@ - +

Dependencies

The code was developed on MSVC 16.9-16.11, MSVC 17.2-17.9, GCC 10.2-13.2, and Clang 11-18, so may be assumed it will work on future releases of these compilers. Minimum required ISO C++ standard is C++20. The Qt framework version used during development was 5.15.2 and >=6.2.

Required
caution

Be aware that the standard support for the last release of the Qt 5 series ended on 26. May 2023. [1][2]

Optional
info

The TinyORM will support Qt versions that aren't end-of-life.

note

You can view the supported database servers in the Database - Getting Started section.

Install dependencies

On Linux, you can install dependencies with the package manager.

MySQL C library
Arch   - pacman -S mariadb-libs
Gentoo - emerge dev-db/mysql (package.use: -server -perl)
Ubuntu - apt install libmysqlclient-dev
range-v3 library (header only)
Arch   - pacman -S range-v3
Gentoo - emerge dev-cpp/range-v3
Ubuntu - apt install librange-v3-dev
ccache
Arch   - pacman -S ccache
Gentoo - emerge dev-util/ccache
Ubuntu - apt install ccache
- + \ No newline at end of file diff --git a/features-summary.html b/features-summary.html index 728e7591e..caf02867a 100644 --- a/features-summary.html +++ b/features-summary.html @@ -14,13 +14,13 @@ - +

Features Summary

Summary List

The following list fastly summarizes all the TinyORM features.

  • simple database connections management 🧬
    • database manager that helps with the database connections management
    • Orm::DB facade class for nicer and shorter syntax
    • MySQL, MariaDB, SQLite, and PostgreSQL support for all features 💎
    • multi-threading support 👀
    • SSL connections support 🔒
  • impressive query builder 🔧
    • allows passing sub-queries and raw expressions practically everywhere, to column names, values, and to every SQL clause as select, where, joins, group by, having, order by 🔥
    • a logical grouping that offers to wrap logical groups in parenthesis
    • chunked results for lower memory footprint ✨
    • raw methods for all SQL clauses
    • all join types (left, right, cross, inner) and also join where clause support 🫤
    • aggregate methods min, max, sum, increment, decrement, ...
    • whereExists and exists methods for an existence queries
    • transactions and pessimistic locking 🔒
    • of course, insert, update, and delete SQL clauses support
    • correct QDateTime time zone using the qt_timezone connection configuration option 📅 (returned QDateTime instances will have the correct time zone, and also works for an ORM)
      • this feature allows you to set up the database server time zone to the UTC and all returned QDateTime instances will have the correct UTC time zone
  • clever ORM with all relation types support 🎉
    • one-to-one, one-to-many, and many-to-many relation types (also inverse relationships) 🧨
    • eager and lazy loading with custom select and constraints 🚀
    • fluent ModelsCollection that expose a variety of map / reduce operations that may be chained using an intuitive interface ✨
    • all query builder methods are proxied from the model instances and also from the relation instances back to the query builder 🤯 (everything that can be called on the query builder can also be called on the model and relation instances)
    • clean active record pattern
    • advanced features like timestamps, touching parent timestamps, soft deleting, default models, default model attributes, and attribute casting 🤓
    • querying relationships existence/absence using the has, whereHas, and hasNested methods (using dot notation for selecting nested relationships users.posts.comments)
    • serializing models and collection of models including all nested relations to JSON and converting to vectors and maps 🪡
      • supports controlling a custom date format during serialization
      • supports hiding and appending attributes
  • compiled database migrations and seeders 🕺
    • create, update, drop, and rename database tables
    • create, drop, and rename table columns
    • extensive schema builder that allows creating of all possible column types
    • terser syntax for creating foreign keys and foreign key constraints
    • supports creating, and dropping column indexes (primary, unique, fulltext, spatial)
  • the tom console application with tab completion for all shells (pwsh, bash, zsh) 🥳
    • scaffolding of models, migrations, and seeders
    • impressive models scaffolding, every feature that is supported by models can be generated using the tom make:model cli command
  • a huge amount of code is unit tested, currently 3366 unit tests 🤯
  • C++20 only, with all the latest features used like concepts/constraints, ranges, smart pointers (no new keyword in the whole code 😎), folding expressions
  • qmake and CMake build systems support
    • CMake FetchContent module support 🤙
  • vcpkg support (also the vcpkg port, currently not committed to the vcpkg repository ☹️)
  • it's really fast, you can run 1000 complex queries in 500ms (heavily DB dependant, the PostgreSQL is by far the fastest) ⌚
  • extensive documentation 📃
  • ...
info

See the TinyDrivers Features summary.

Showcase Images

Tom console application
TinyORM - Tom console application - Showcase
Passed all unit tests 🥳
TinyORM - Passed all unit tests - Showcase

TinyOrmPlayground

The TinyOrmPlayground project is my personal project where I have tested all the TinyORM database queries in the early development phases, currently, it executes ~1600 database queries across the whole TinyORM framework. Every query has a nice title header, is logged to the console, and is counted and measured (elapsed time). Every query also runs on all supported databases.

The TinyOrmPlayground project can be compiled in a single-threaded or multi-threaded mode. In the multi-threaded mode, every database connection runs in its own thread. At the end of every database connection is logged a connection summary and before an exit is logged the application summary. Whole TinyOrmPlayground application is configurable through the src/configuration.hpp class.

TinyOrmPlayground single-threaded
TinyORM - Invoked TinyOrmPlayground single-threaded - Showcase
TinyOrmPlayground multi-threaded
TinyORM - Invoked TinyOrmPlayground multi-threaded - Showcase
- + \ No newline at end of file diff --git a/index.html b/index.html index 2f49c29b9..9aeb33651 100644 --- a/index.html +++ b/index.html @@ -14,13 +14,13 @@ - +
-

Prologue

TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries.

The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests. Almost all the query builder methods are unit tested. The TinyORM's query builder code and the code which is responsible for obtaining relationships, is tested by functional tests against all supported databases. The code coverage is good enough to guarantee API and behavior compatibility.

tip

For a quick look at what's inside, check out the Features Summary.

info

If you don't want to use full ORM, then you can use only the Query Builder, which is outstanding. 🔥 This way you can avoid writing raw SQL queries and your code will run on all supported databases.

Documentation Sitemap
Current versions
  • TinyORM v0.37.0
  • tom v0.8.0
  • TinyDrivers v0.1.0
  • TinyMySql v0.1.0
- +

Prologue

TinyORM is a modern C++ ORM library that makes interacting with a database extremely simple. It depends on the QtCore and QtSql libraries.

The code is written in the modern C++20 way and is heavily tested with 3366 unit and functional tests. Almost all the query builder methods are unit tested. The TinyORM's query builder code and the code which is responsible for obtaining relationships, is tested by functional tests against all supported databases. The code coverage is good enough to guarantee API and behavior compatibility.

tip

For a quick look at what's inside, check out the Features Summary.

info

If you don't want to use full ORM, then you can use only the Query Builder, which is outstanding. 🔥 This way you can avoid writing raw SQL queries and your code will run on all supported databases.

Documentation Sitemap
Current versions
  • TinyORM v0.37.1
  • tom v0.9.0
  • TinyDrivers v0.1.0
  • TinyMySql v0.1.0
+ \ No newline at end of file diff --git a/search.html b/search.html index a122be5fc..949c262fa 100644 --- a/search.html +++ b/search.html @@ -14,13 +14,13 @@ - +

Search the documentation

- + \ No newline at end of file diff --git a/sponsors.html b/sponsors.html index fa1503c40..a43ffa33a 100644 --- a/sponsors.html +++ b/sponsors.html @@ -14,13 +14,13 @@ - +

Sponsors

I have spent ~2 years every day 10 hours of coding (excluding weekends and sick days) to make this project real. Everything was funded from my personal resources, I had no problem with it to be honest, it was really fun 🎉, but I had to move to the new apartment a few months ago and I'm out of money now. ☹️

I would like to continue developing and enhancing this project and I will as long as I can. But the future is unclear now.

ServiceAddress
Bitcoin address1NiF2cTvYxUj8FTZJnGn1ycN4yisWfo1vJ
PayPalhttps://paypal.me/silverzachara
- + \ No newline at end of file diff --git a/supported-compilers.html b/supported-compilers.html index 4eb06d7ac..b95b11613 100644 --- a/supported-compilers.html +++ b/supported-compilers.html @@ -14,13 +14,13 @@ - +

Supported Compilers

Following compilers are backed up by the GitHub Action workflows (CI pipelines), these workflows also include more then 3366 unit tests 😮💥.

Windows >=10

  • MSVC 2019 >=16.9
  • MSVC 2022 >=17
  • MSYS2 UCRT64 GCC 10.2 - 13.2
  • MSYS2 UCRT64 Clang >=15
  • clang-cl >=15 with MSVC 2019/2022

Linux

  • GCC 10.2 - 13.2
  • Clang >=15 (libstdc++ only)
tip

You can compile TinyORM with the MSVC 2022 even if Qt doesn't provide binaries for the MSVC 2022, you can link against Qt MSVC 2019 binaries without any limitations.

caution

The macOS and Clang with libc++ are not supported.

Supported build systems

  • CMake >=3.22 (policies <= CMP0128 default to NEW)
  • qmake distributed by the Qt Framework
Make tools
  • jom - highly recommended with the qmake build system on Windows (replacement for nmake)
  • ninja - recommended for CMake as the make file generator
Parallel building

You can control parallel building using the following environment variables.

  • CMake - CMAKE_BUILD_PARALLEL_LEVEL eg. to 10
  • jom - JOMFLAGS eg. to j11
  • make - MAKEFLAGS eg. to -j10
  • vcpkg - VCPKG_MAX_CONCURRENCY eg. to 10
- + \ No newline at end of file diff --git a/tinydrivers/getting-started.html b/tinydrivers/getting-started.html index 0b562bcfe..f5b1682b9 100644 --- a/tinydrivers/getting-started.html +++ b/tinydrivers/getting-started.html @@ -14,13 +14,13 @@ - +

TinyDrivers: Getting Started

Introduction

The TinyDrivers library is an underlying SQL database layer for TinyORM. It can be used instead of the QtSql module, can be swapped at compile, and has 1:1 API as the QtSql module. 😮 Swapping is controlled by the qmake and CMake build system options.

It was designed to drop the QtSql dependency while maintaining backward compatibility and without the need for any code changes after the swap.

Features summary
  • both, normal and prepared statements are supported
  • TLS/SSL connections using MYSQL_OPT_SSL_MODE (verify_ca, verify_identity) 🔥
  • setting many other connection options (see mysqldriver_p.cpp)
  • building and linking against the MariaDB Connector/C
  • transactions
  • re-using the current SqlQuery instance to re-execute the same or another query
  • detaching from the result set (associated to release memory)
  • query size, number of affected rows, last inserted ID, testing isNull(), ...
  • all 3366 unit tests passed 😮
info

Currently, only the MySQL database driver is supported and finished.

info

TinyDrivers can only be built with Qt v6, Qt v5.15 isn't supported.

note

TinyDrivers library supports both build systems qmake and also CMake.

Differences from QtSql

TinyDrivers doesn't return errors the the same way as the QtSql module, which means return a bool and if it's the result false then obtain the SqlError instance using the lastError() method from SqlDatabase or SqlQuery instances. Instead, it throws exceptions, and methods returning a bool type to report an error state always return true.

Naming conventions
  • QtSql module -> TinyDrivers library
  • QMYSQL driver -> TinyMySql driver
MySQL driver

The following describes the differences between QMYSQL and TinyMySql drivers.

The QMYSQL driver doesn't support setting MySQL non-flag connection options like MYSQL_OPT_RECONNECT without the value, it needs to be defined with value like =1 or =TRUE (case-sensitive), only real flag options like CLIENT_INTERACTIVE can be set without the value and = character.

On the other hand, the TinyMySql driver allows setting non-flag connection options options without the value and = character, which are considered enabled (ON or TRUE).

Removed features

Simulation of prepared statements while calling SqlQuery::exec(QString), this functionality is useless because you can call regular prepared statements using SqlQuery::prepare(QString) and then SqlQuery::exec().

Missing features

Fetching multiple result sets using SqlQuery::nextResult(). Multiple statement queries are supported they will be executed correctly (they can return multiple result sets), but only the first result set can be fetched currently. However, destroying multiple result sets is handled correctly.

Build system

Another difference is that you can build the TinyDrivers and its SQL drivers (TinyMySql) in 3 different ways; Shared, Static, and as a Loadable library at runtime using LoadLibrary() on Windows or dlopen() on Linux.

The Shared library build

It builds two shared libraries, the TinyDrivers shared library that contains the core/common code and the TinyMySql shared library that contains MySQL implementation. The TinyOrm links only against the TinyDrivers shared library and TinyMySql is a private implementation.

The Static build

It builds one TinyDrivers static archive that contains the core/common code and SQL drivers (TinyMySql). This static library is linked or merged into the TinyOrm shared or static library (both variants are supported).

The Loadable SQL drivers build

It builds two shared libraries, the TinyDrivers shared library that contains the core/common code and TinyMySql shared library (module) that contains MySQL implementation that is loaded at runtime using LoadLibrary() on Windows or dlopen() on Linux. The SQL driver library loader throws an exception if it cannot find this library at runtime.

info

The TinyMySql links directly against the MySQL C connector (libmysql or mysqlclient library).

CMake/qmake build options

For CMake

See CMake build options, related CMake build options are:
BUILD_DRIVERS, BUILD_MYSQL_DRIVERS, and DRIVERS_TYPE

To control shared and static build use BUILD_SHARED_LIBS CMake configuration option.

For qmake

See qmake build options, related qmake configuration options are:
build_loadable_drivers, build_mysql_driver, build_shared_drivers, and build_static_drivers

To control shared and static build use staticlib qmake configuration option.

Performance

Performance is several milliseconds faster compared to QtSql with the QMYSQL driver. It was tuned using the KCacheGrind to be so. It's ~40ms faster on TinyOrmPlayground project with 620 database queries compiled using GCC v13.2.1 Debug build on Linux. Similar results can be expected on other platforms but it's not guaranteed.

This means performance is very similar to QtSql. There is not much to speed up because TinyDrivers code is swift and 90% of the time is spent inside the MySQL C API because we always have to wait for the database server, especially when creating database connections using eg. mysql_real_connect() (this function is king among the slowest functions 😎, which is understandable of course).

Internals

TinyDrivers internal design can be divided into 3 different layers:

  • Driver layer
  • SQL API layer
  • Public API layer

The Driver layer is eg. TinyMySql library which is responsible for communicating with the underlying database driver (eg. MySQL C API).

The SQL API layer is a semi-layer that glues everything up and sits between the Public interface API and the Driver layer.

The Public interface API layer are the end classes like SqlDatabase and SqlQuery which are exposed to the end user.

SqlDatabase

One more thing worth mentioning is the SqlDatabase API. It's one class that has two responsibilities! All static methods act as the database connection manager and an instance of the SqlDatabase represents a physical database connection. It's not a good design because it breaks the Single Responsibility principle, but it's what it is.

Namespaces

TinyDrivers classes are defined in the Orm::Drivers namespace and TinyMySql classes in the Orm::Drivers::MySql namespace.

Documentation

For all other APIs you can follow the QtSql documentation as the API is 1:1. The exception is of course the build system, TinyOrm has its own build system that doesn't follow the QtSql module.

- + \ No newline at end of file diff --git a/tinyorm/casts.html b/tinyorm/casts.html index 34116611d..f3e280e2e 100644 --- a/tinyorm/casts.html +++ b/tinyorm/casts.html @@ -14,14 +14,14 @@ - +

TinyORM: Casting

Introduction

Attribute casting allows you to transform TinyORM attribute values when you retrieve them on model instances. For example, you may want to convert a datetime string that is stored in your database to the QDateTime instance when it is accessed via your TinyORM model. Or, you may want to convert a tinyint number that is stored in the database to the bool when you access it on the TinyORM model.

Accessors

caution

Accessors are currently only used during the serialization by the Appending Values feature. They are not used during the getAttribute or getAttributeValue methods calls.

Defining An Accessor

An accessor transforms a TinyORM attribute value when it is accessed (currently during serialization only by the Appending Values feature). To define an accessor, create a protected method on your model to represent the accessible attribute. This method name should correspond to the "camelCase" representation of the true underlying model attribute / database column when applicable.

In this example, we'll define an accessor for the first_name attribute. The accessor will automatically be called by TinyORM during serialization if the first_name attribute is defined in the u_appends data member set. All attribute accessor methods must return the Orm::Tiny::Casts::Attribute:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class User final : public Model<User>
{
friend Model;
using Model::Model;

protected:
/*! Get the user's first name (accessor). */
Attribute firstName() const noexcept
{
return Attribute::make(/* get */ [this]() -> QVariant
{
auto firstName = getAttribute<QString>("first_name");

if (!firstName.isEmpty())
firstName[0] = firstName.at(0).toUpper();

return firstName;
});
}

private:
/*! Map of mutator names to methods. */
inline static const QHash<QString, MutatorFunction> u_mutators {
{"first_name", &User::firstName},
};
};

All accessor methods return an Attribute instance which defines how the attribute will be accessed. To do so, we supply the get argument to the Attribute class constructor or Attribute::make factory method.

As you can see, the current model is captured by-reference using the [this] capture, allowing you to obtain a value by the getAttribute method inside the lambda expression, manipulate it and return a new value.

You can also use the second overload that allows you to pass the ModelAttributes unordered map to the lambda expression:

protected:
/*! Get the user's first name (accessor). */
Attribute firstName() const noexcept
{
return Attribute::make(
/* get */ [](const ModelAttributes &attributes) -> QVariant
{
auto firstName = attributes.at<QString>("first_name");

if (!firstName.isEmpty())
firstName[0] = firstName.at(0).toUpper();

return firstName;
});
}

The ModelAttributes container extends the std::unordered_map<QString, QVariant> and adds the at<T> method that allows you to cast the underlying QVariant value.

Special note should be given to the u_mutators static data member map, which maps accessors' attribute names to its methods. This data member is required because C++ does not currently support reflection.

info

If you would like these computed values to be added to the vector, map, or JSON representations of your model, you will need to append them.

danger

You must guarantee that the current model will live long enough to avoid the dangling reference and crash if the current model is captured by-reference. Of course, you can capture it by-copy in edge cases or if you can't guarantee this.

Building Value From Multiple Attributes

Sometimes your accessor may need to transform multiple model attributes into a single value. You can use both methods described above to accomplish this:

using Orm::Constants::SPACE_IN;

protected:
/*! Get the user's full name (accessor). */
Attribute fullName() const noexcept
{
return Attribute::make(/* get */ [this]() -> QVariant
{
return SPACE_IN.arg(getAttribute<QString>("first_name"),
getAttribute<QString>("last_name"));
});
}

Or you can use the ModelAttributes overload:

/*! Get the user's full name (accessor). */
Attribute fullName() const noexcept
{
return Attribute::make(
/* get */ [](const ModelAttributes &attributes) -> QVariant
{
return SPACE_IN.arg(attributes.at<QString>("first_name"),
attributes.at<QString>("last_name"));
});
}

Accessor Caching

Sometimes computing an attribute value can be intensive, in this case, you can enable caching for this attribute value. To accomplish this, you have to invoke the shouldCache method when defining your accessor:

using Orm::Constants::SPACE_IN;

protected:
/*! Get the user's full name (accessor). */
Attribute fullName() const noexcept
{
return Attribute::make(/* get */ [this]() -> QVariant
{
return SPACE_IN.arg(getAttribute<QString>("first_name"),
getAttribute<QString>("last_name"));
}).shouldCache();
}

Attribute Casting

Attribute casting provides functionality that allows converting model attributes to the appropriate QVariant metatype when it is accessed via your TinyORM model. The core of this functionality is a model's u_casts static data member that provides a convenient method of converting attributes' QVariant internal types to the defined cast types.

The u_casts static data member should be the std::unordered_map<QString, Orm::CastItem> where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are:

  • CastType::QString
  • CastType::Boolean / CastType::Bool
  • CastType::Integer / CastType::Int
  • CastType::UInteger / CastType::UInt
  • CastType::LongLong
  • CastType::ULongLong
  • CastType::Short
  • CastType::UShort
  • CastType::QDate
  • CastType::QDateTime
  • CastType::Timestamp
  • CastType::Real
  • CastType::Float
  • CastType::Double
  • CastType::Decimal:<precision>
  • CastType::QByteArray
info

The primary key name defined by the u_primaryKey model's data member is automatically cast to the CastType::ULongLong for all database drivers if the u_incrementing is set to true (its default value).

To demonstrate attribute casting, let's cast the is_admin attribute, which is stored in our database as an integer (0 or 1) to a QVariant(bool) value:

#pragma once

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class User final : public Model<User>
{
friend Model;
using Model::Model;

/*! The attributes that should be cast. */
inline static std::unordered_map<QString, CastItem> u_casts {
{"is_admin", CastType::Boolean},
};
};

After defining the cast, the is_admin attribute will always be cast to a QVariant(bool) when you access it, even if the underlying value is stored in the database as an integer:

using Orm::Utils::Helpers;

auto isAdmin = User::find(1)->getAttribute("is_admin");

// Proof of the QVariant type
Q_ASSERT(Helpers::qVariantTypeId(isAdmin) == QMetaType::Bool);

if (isAdmin.value<bool>()) {
//
}

If you need to add a new, temporary cast at runtime, you may use the mergeCasts method. These cast definitions will be added to any of the casts already defined on the model:

user->mergeCasts({
{"is_paid", CastType::Boolean},
{"income", {CastType::Decimal, 2}},
});
caution

You should never define a cast (or an attribute) that has the same name as a relationship.

info

Attributes that are null will also be cast so that the QVariant's internal type will have the correct type.

Date Casting

By default, TinyORM will cast the created_at and updated_at columns to instances of QDateTime. You may cast additional date attributes by defining additional date casts within your model's u_casts static data member unordered map. Typically, dates should be cast using the CastType::QDateTime, CastType::QDate, or CastType::Timestamp cast types.

When a database column is of the date type, you may set the corresponding model attribute value to a UNIX timestamp, date string (Y-m-d), date-time string, QDate, or QDateTime instance. The date's value will be correctly converted and stored in your database.
The same is true for the datetime or timestamp database column types, you can set the corresponding model attribute value to a UNIX timestamp, date-time string, or a QDateTime instance.

When defining the CastType::QDate or CastType::QDateTime cast, you may also specify the date's format. In this case you must use the CastType::CustomQDate or CastType::CustomQDateTime cast types. This format will be used when the model is serialized to a vector, map, or JSON:

/*! The attributes that should be cast. */
inline static std::unordered_map<QString, CastItem> u_casts {
{"created_at", {CastType::CustomQDateTime, "yyyy-MM-dd"}},
};
note

The CastType::CustomQDate and CastType::CustomQDateTime cast types behave exactly like the CastType::QDate and CastType::QDateTime cast types with the additional date's format functionality during serialization.

You may customize the default serialization format for all of your model's dates or datetimes by defining a serializeDate or serializeDateTime methods on your model. These methods do not affect how your dates are formatted for storage in the database:

/*! Prepare a date for vector, map, or JSON serialization. */
QString serializeDate(const QDate date)
{
return date.toString("yyyy-MM-dd");
}

/*! Prepare a datetime for vector, map, or JSON serialization. */
QString serializeDateTime(const QDateTime &datetime)
{
return datetime.toUTC().toString("yyyy-MM-ddTHH:mm:ssZ");
}

To specify the format that should be used when actually storing a model's dates within your database, you should define a u_dateFormat data member on your model:

/*! The storage format of the model's date columns. */
inline static QString u_dateFormat {QLatin1Char('U')};

This format can be any format that the QDateTime's fromString or toString methods accept or the special U format that represents the UNIX timestamp (this U format is TinyORM-specific and isn't supported by QDateTime).

Define a u_timeFormat data member on your model to specify the format that should be used when storing a model's times within your database:

/*! The storage format of the model's time columns. */
inline static QString u_timeFormat {"HH:mm:ss.zzz"};

Date Casting, Serialization & Timezones

By default, the CastType::CustomQDate and CastType::CustomQDateTime casts will serialize dates to a UTC ISO-8601 date string (yyyy-MM-ddTHH:mm:ss.zzzZ), regardless of the timezone specified in your database connection's qt_timezone configuration option. You are strongly encouraged to always use this serialization format, as well as to store your application's dates in the UTC timezone by not changing your database connection's qt_timezone configuration option from its default Qt::UTC value. Consistently using the UTC timezone throughout your application will provide the maximum level of interoperability with other date manipulation libraries or services written in any programming language.

If a custom format is applied to the CastType::CustomQDate or CastType::CustomQDateTime cast types, such as {CastType::CustomQDateTime, "yyyy-MM-dd HH:mm:ss"}, the inner timezone of the QDateTime instance will be used during date serialization. Typically, this will be the timezone specified in your database connection's qt_timezone configuration option.

Query Time Casting

Sometimes you may need to apply casts while executing a query, such as when selecting a raw value from a table. For example, consider the following query:

using Models::Post;
using Models::User;

auto users = User::select("users.*")
->addSelect(
Post::selectRaw("MAX(created_at)")
->whereColumnEq("user_id", "users.id")
.toBase(),
"last_posted_at"
).get();

The last_posted_at attribute on the results of this query will be a simple string. It would be wonderful if we could apply a CastType::QDateTime cast to this attribute when executing the query. Thankfully, we may accomplish this using the withCasts or withCast methods:

auto users = User::select("users.*")
->addSelect(Post::selectRaw("MAX(created_at)")
->whereColumnEq("user_id", "users.id")
.toBase(),
"last_posted_at")
.withCast({"last_posted_at", CastType::QDateTime})
.get();
- + \ No newline at end of file diff --git a/tinyorm/collections.html b/tinyorm/collections.html index 45db8be0f..54b50f0ba 100644 --- a/tinyorm/collections.html +++ b/tinyorm/collections.html @@ -14,7 +14,7 @@ - + @@ -71,7 +71,7 @@ whereNotIn whereNotNull whereNull

note

For a better understanding of the following examples, many of the variable declarations below use actual types instead of the auto keyword.

all()

The all method returns a copy of the underlying vector represented by the collection:

QVector<User> = users.all();
note

The toBase is an alias to the all method.

contains()

The contains method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance:

users.contains(1);

users.contains(User::find(1));

Alternatively, you may pass a lambda expression to the contains method to determine if a model exists in the collection matching a given truth test:

users.contains([](const User *const user)
{
return user->getKeyCasted() == 2;
});

For the inverse of contains, see the doesntContain method.

doesntContain()

The doesntContain method determines whether the collection does not contain a given item. This method accepts a primary key or a model instance:

users.doesntContain(1);

users.doesntContain(User::find(1));

Alternatively, you may pass a lambda expression to the doesntContain method to determine if a model does not exist in the collection matching a given truth test:

users.doesntContain([](const User *const user)
{
return user->getKeyCasted() == 2;
});

For the inverse of doesntContain, see the contains method.

each()

The each method iterates over the models in the collection and passes each model to the lambda expression:

ModelsCollection<User> users = Post::whereEq("user_id", 1)->get();

users.each([](User *const user)
{
// ...
});

If you would like to stop iterating through the models, you may return false from your lambda expression:

users.each([](User *const user)
{
if (/* condition */)
return false;

// Some logic

return true;
});

You may also pass the lambda expression with two parameters, whereas the second one is an index:

users.each([](User *const user, const std::size_t index)
{
// ...
});

The each method returns an lvalue reference to the currently processed collection.

It can be also called on ModelsCollection rvalues, it returns an rvalue reference in this case.

except()

The except method returns all of the models that do not have the given primary keys:

ModelsCollection<User *> usersResult = users.except({1, 2, 3});

All of the models are returned if the ids argument is empty except({}).

The order of models in the collection is preserved.

For the inverse of except, see the only method.

filter()

The filter method filters the collection using the lambda expression, keeping only those models that pass a given truth test:

auto usersBanned = users.filter([](const User *const user)
{
return user->getAttribute<bool>("is_banned");
});

You may also pass the lambda expression with two parameters, whereas the second one is an index:

auto usersBanned = users.filter([](const User *const user,
const std::size_t index)
{
return index < 10 && user->getAttribute<bool>("is_banned");
});

If no lambda expression is supplied, all models of the collection that are equivalent to the nullptr will be removed:

ModelsCollection<User> usersRaw = User::findMany({1, 2});
ModelsCollection<User *> users {&usersRaw[0], nullptr, &usersRaw[1]};

ModelsCollection<User *> filtered = users.filter();

// {1, 2}

For the inverse of filter, see the reject method.

find()

The find method returns the model that has a primary key matching the given key:

User *const user = users.find(1);

If you pass a model instance, find will attempt to return a model matching the primary key:

User *user = users.find(anotherUser);

The two overloads above also accept the second defaultModel model argument, which will be returned if a model was not found in the collection, its default value is the nullptr.

Alternatively, may pass more IDs and find will return all models which have a primary key within the given unordered set:

ModelsCollection<User *> usersMany = users.find({1, 2});

This overload internally calls the only method.

first()

The first method returns the first model in the collection that passes a given truth test:

ModelsCollection<User> users {
{{"name", "Kate"}, {"votes", 150}},
{{"name", "John"}, {"votes", 200}},
{{"name", "Jack"}, {"votes", 400}},
};

User *user = users.first([](User *const user)
{
return user->getAttribute<quint64>("votes") > 150;
});

// {{"name", "John"}, {"votes", 200}}

If no model passes a given truth test then the value of the second defaultModel argument will be returned, its default value is the nullptr.

using NullVariant = Orm::Utils::NullVariant;

User defaultUser {{"name", NullVariant::QString()},
{"votes", NullVariant::ULongLong()}};

User *user = users.first([](User *const user)
{
return user->getAttribute<quint64>("votes") > 500;
},
&defaultUser);

/*
{{"name", NullVariant::QString()},
{"votes", NullVariant::ULongLong()}}
*/

You can also call all first overloads provided by the QList::first.

firstWhere()

The firstWhere method returns the first model in the collection with the given column / value pair:

using NullVariant = Orm::Utils::NullVariant;

ModelsCollection<User> users {
{{"name", "Leon"}, {"age", NullVariant::UShort()}},
{{"name", "Jill"}, {"age", 14}},
{{"name", "Jack"}, {"age", 23}},
{{"name", "Jill"}, {"age", 84}},
};

auto user = users.firstWhereEq("name", "Linda");

// {{"name", "Jill"}, {"age", 14}}

You may also call the firstWhere method with a comparison operator:

users.firstWhere("age", ">=", 18);

// {{"name", "Jack"}, {"age", 23}}

fresh()

The fresh method retrieves a fresh instance of each model in the collection from the database. In addition, any specified relationships will be eager loaded:

auto usersFresh = users.fresh();

auto usersFresh = users.fresh("comments");

auto usersFresh = users.fresh("posts:id,name");

auto usersFresh = users.fresh({"comments", "posts:id,name"});

The relations argument format is the same as for TinyBuilder's load method.

implode()

The implode method joins attributes by the given column and the "glue" string you wish to place between the values:

ModelsCollection<Product> products {
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 100}},
};

products.implode("product", ", ");

// {Desk, Chair}

The default "glue" value is an empty string "".

isEmpty()

The isEmpty method returns true if the collection is empty; otherwise, false is returned:

ModelsCollection<User>().isEmpty();

// true

isNotEmpty()

The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned:

ModelsCollection<User>().isNotEmpty();

// false

last()

The last method returns the last model in the collection that passes a given truth test:

ModelsCollection<User> users {
{{"name", "Kate"}, {"votes", 150}},
{{"name", "John"}, {"votes", 200}},
{{"name", "Jack"}, {"votes", 400}},
{{"name", "Rose"}, {"votes", 350}},
};

User *user = users.last([](User *const user)
{
return user->getAttribute<quint64>("votes") < 300;
});

// {{"name", "John"}, {"votes", 200}}

If no model passes a given truth test then the value of the second defaultModel argument will be returned, its default value is the nullptr.

using NullVariant = Orm::Utils::NullVariant;

User defaultUser {{"name", NullVariant::QString()},
{"votes", NullVariant::ULongLong()}};

User *user = users.last([](User *const user)
{
return user->getAttribute<quint64>("votes") < 100;
},
&defaultUser);

/*
{{"name", NullVariant::QString()},
{"votes", NullVariant::ULongLong()}}
*/

You can also call all last overloads provided by the QList::last.

load()

The load method eager loads the given relationships for all models in the collection:

users.load({"comments", "posts"});

users.load("comments.author");

users.load({{"comments"}, {"posts", [](auto &query)
{
query.whereEq("active", true);
}}});

The relations argument format is the same as for TinyBuilder's load method.

map()

The map method iterates through the collection and passes a copy of each model to the given lambda expression. The lambda expression is free to modify the model and return it, thus forming a new collection of modified models:

ModelsCollection<User> users {
{{"name", "John"}, {"votes", 200}},
{{"name", "Jack"}, {"votes", 400}},
};

auto usersAdded = users.map([](User &&userCopy)
{
if (userCopy.getAttribute<QString>("name") == "John")
userCopy["votes"] = userCopy.getAttribute<quint64>("votes") + 1;

return std::move(userCopy);
});

/*
{
{{"name", "John"}, {"price", 201}},
{{"name", "Jack"}, {"price", 400}},
}
*/

The second map overload allows to return the QVector<T>:

QVector<quint64> usersAdded = users.map<quint64>([](User &&userCopy)
{
const auto votesRef = userCopy["votes"];

if (userCopy.getAttribute<QString>("name") == "John")
votesRef = userCopy.getAttribute<quint64>("votes") + 1;

return votesRef->value<quint64>();
});

// {201, 400}

Both overloads allow to pass the lambda expression with two arguments, whereas the second argument can be an index of the std::size_t type.

caution

Like most other collection methods, map returns a new collection instance; it does not modify the collection it is called on. If you want to modify the original collection in place, use the each method.

info

The model copy is passed to the lambda expression even if the map iterates over a collection of model pointers ModelsCollection<Model *>. The models are dereferenced behind the scene.

mapWithKeys()

The mapWithKeys method iterates through the collection and passes each model to the given lambda expression. It returns the std::unordered_map<K, V> and the lambda expression should return the std::pair<K, V> containing a single column / value pair:

ModelsCollection<User> users {
{{"id", 1}, {"name", "John"}, {"email", "john@example.com"}},
{{"id", 2}, {"name", "Jill"}, {"email", "jill@example.com"}},
};

auto usersMap = users.mapWithKeys<quint64, QString>(
[](User *const user) -> std::pair<quint64, QString>
{
return {user->getKeyCasted(), user->getAttribute<QString>("name")};
});

// {{1, 'John'}, {2, 'Jill'}}

You can also map IDs to the model pointers:

auto usersMap = users.mapWithKeys<quint64, User *>(
[](User *const user) -> std::pair<quint64, User *>
{
return {user->getKeyCasted(), user};
});

mapWithModelKeys()

The mapWithModelKeys maps the primary keys to the Model *, it returns the std::unordered_map<Model::KeyType, Model *>:

auto usersMap = users.mapWithModelKeys();

modelKeys()

The modelKeys method returns the primary keys for all models in the collection:

ModelsCollection<User> users {
{{"id", 1}, {"name", "John"}},
{{"id", 2}, {"name", "Jill"}},
{{"id", 3}, {"name", "Kate"}},
{{"id", 5}, {"name", "Rose"}},
};

users.modelKeys(); // Returns QVector<QVariant>
users.modelKeys<quint64>();

// {1, 2, 3, 5}

only()

The only method returns all of the models that have the given primary keys:

ModelsCollection<User *> usersResult = users.only({1, 2, 3});

An empty collection is returned if the ids argument is empty only({}).

The order of models in the collection is preserved.

For the inverse of only, see the except method.

pluck()

The pluck method retrieves all of the values for a given column, the following overload returns the QVector<QVariant>:

ModelsCollection<Product> products {
{{"id", 1}, {"name", "Desk"}},
{{"id", 2}, {"name", "Chair"}},
};

auto plucked = products.pluck("name");

// {Desk, Chair}

The second overload allows returning the custom type QVector<T>:

auto plucked = products.pluck<QString>("name");

You may also specify how you wish the resulting collection to be keyed, this overload returns the std::map<T, QVariant>:

auto plucked = products.pluck<quint64>("name", "id");

// {{1, "Desk"}, {2, "Chair"}}

If duplicate keys exist, the last matching attribute will be inserted into the plucked collection:

ModelsCollection<Product> collection {
{{"brand", "Tesla"}, {"color", "red"}},
{{"brand", "Pagani"}, {"color", "white"}},
{{"brand", "Tesla"}, {"color", "black"}},
{{"brand", "Pagani"}, {"color", "orange"}},
};

auto plucked = collection.pluck<QString>("color", "brand");

// {{'Tesla', 'black'}, {'Pagani', 'orange"}}

reject()

The reject method filters the collection using the given lambda expression. The lambda should return true if the model should be removed from the resulting collection:

auto usersWithNote = users.reject([](const User *const user)
{
return user->getAttribute("note").isNull();
});

You may also pass the lambda expression with two arguments, whereas the second argument can be an index of the std::size_t type.

For the inverse of the reject method, see the filter method.

sort()

The sort method sorts the models collection by primary keys:

ModelsCollection<User> users {
{{"id", 2}, {"name", "Kate"}},
{{"id", 3}, {"name", "John"}},
{{"id", 1}, {"name", "Jack"}},
};

auto sorted = users.sort();

/*
{
{{"id", 1}, {"name", "Jack"}},
{{"id", 2}, {"name", "Kate"}},
{{"id", 3}, {"name", "John"}},
}
*/

You may pass a predicate and projection callbacks to the sort method with your own algorithms. Refer to the CPP reference documentation on ranges::sort, which is what the sort method calls internally.

You can eg. sort by multiple columns, for an alternative method of multi-column sorting look at sortBy:

ModelsCollection<User> users {
{{"name", "Kate"}, {"votes", 350}},
{{"name", "John"}, {"votes", 200}},
{{"name", "John"}, {"votes", 150}},
{{"name", "Kate"}, {"votes", 200}},
};

auto sorted = users.sort([](const User *const left,
const User *const right)
{
const auto leftValue = left->getAttribute<QString>("name");
const auto rightValue = right->getAttribute<QString>("name");

if (leftValue == rightValue)
return left->getAttribute<quint64>("votes") <
right->getAttribute<quint64>("votes");

return leftValue < rightValue;
});

/*
{
{{"name", "John"}, {"votes", 150}},
{{"name", "John"}, {"votes", 200}},
{{"name", "Kate"}, {"votes", 200}},
{{"name", "Kate"}, {"votes", 350}},
}
*/

The order of equal elements is not guaranteed to be preserved.

info

You can use the stable sort method variants to preserve the order of equal models.

sortBy()

The sortBy method sorts the collection by the given column, this overload needs the template argument so it can cast the attribute value before comparing:

ModelsCollection<User> users {
{{"name", "Kate"}, {"votes", 150}},
{{"name", "John"}, {"votes", 200}},
{{"name", "Jack"}, {"votes", 400}},
};

auto sorted = users.sortBy<QString>("name");

/*
{
{{"name", "Jack"}, {"votes", 400}},
{{"name", "John"}, {"votes", 200}},
{{"name", "Kate"}, {"votes", 150}},
}
*/

You may pass the projection callback to determine how to sort the collection's models:

auto sorted = users.sortBy([](User *const user)
{
return user->getAttribute<quint64>("votes");
});

/*
{
{{"name", "Kate"}, {"votes", 150}},
{{"name", "John"}, {"votes", 200}},
{{"name", "Jack"}, {"votes", 400}},
}
*/

If you would like to sort your collection by multiple columns, you may pass a vector of comparison lambda expressions that define each sort operation to the sortBy method, in the following example is the name column sorted in ascending order and the second votes column is sorted in descending order:

using AttributeUtils = Orm::Tiny::Utils::Attribute;

ModelsCollection<User> users {
{{"name", "Kate"}, {"votes", 350}},
{{"name", "John"}, {"votes", 200}},
{{"name", "John"}, {"votes", 150}},
{{"name", "Kate"}, {"votes", 200}},
};

auto sorted = users.sortBy({
[](const User *const left, const User *const right)
{
return AttributeUtils::compareForSortBy(
left->getAttribute<QString>("name"),
right->getAttribute<QString>("name"));
},
[](const User *const left, const User *const right)
{
return AttributeUtils::compareForSortByDesc(
left->getAttribute<quint64>("votes"),
right->getAttribute<quint64>("votes"));
},
});

/*
{
{{"name", "John"}, {"votes", 200}},
{{"name", "John"}, {"votes", 150}},
{{"name", "Kate"}, {"votes", 350}},
{{"name", "Kate"}, {"votes", 200}},
}
*/

The AttributeUtils::compareForSortBy and compareForSortByDesc methods are helper methods, they are needed because the Qt framework doesn't define <=> spaceship operator on its types, it doesn't support the three-way comparison.

The order of equal elements is not guaranteed to be preserved.

sortByDesc()

This method has the same signature as the sortBy method but will sort the collection in the opposite order.

The order of equal elements is not guaranteed to be preserved.

sortDesc()

This method will sort the collection in the opposite order as the sort method:

ModelsCollection<User> users {
{{"id", 2}, {"name", "Kate"}},
{{"id", 3}, {"name", "John"}},
{{"id", 1}, {"name", "Jack"}},
};

auto sorted = users.sortDesc();

/*
{
{{"id", 3}, {"name", "John"}},
{{"id", 2}, {"name", "Kate"}},
{{"id", 1}, {"name", "Jack"}},
}
*/

The order of equal elements is not guaranteed to be preserved.

stableSort()

This method has the same signature as the sort method but will preserve the order of equal elements (guaranteed to be preserved).

stableSortBy()

This method has the same signature as the sortBy method but will preserve the order of equal elements (guaranteed to be preserved).

stableSortByDesc()

This method has the same signature as the sortByDesc method but will sort the collection in the opposite order and preserve the order of equal elements (guaranteed to be preserved).

stableSortDesc()

This method has the same signature as the sortDesc method but will sort the collection in the opposite order and preserve the order of equal elements (guaranteed to be preserved).

tap()

The tap method passes a collection to the given lambda expression, allowing you to "tap" into the collection at a specific point and do something with the models while not affecting the collection itself:

ModelsCollection<User> users {
{{"id", 2}, {"name", "Kate"}},
{{"id", 3}, {"name", "John"}},
{{"id", 1}, {"name", "Jack"}},
};

users.sort()
.tap([](/*const */ModelsCollection<User *> &usersRef)
{
qDebug() << "IDs after sorting:"
<< usersRef.template modelKeys<quint64>();
})
.value<quint64>("id");

// 1

The tap method returns an lvalue reference to the currently processed collection.

It can be also called on ModelsCollection rvalues, it returns an rvalue reference in this case.

toBase()

The toBase method returns a copy of the underlying vector represented by the collection:

QVector<User> = users.toBase();
note

The toBase is an alias to the all method.

toJson()

The toJson method converts the collection of models with all nested relations into a JSON serialized QByteArray.

It returns an empty array for empty many type relations and null for empty one type relations.

info

The toJson method accepts the QJsonDocument::JsonFormat, possible values are QJsonDocument::Indented or QJsonDocument::Compact.

toJsonArray()

The toJsonArray method converts the collection of models with all nested relations into a QJsonArray.

toJsonDocument()

The toJsonDocument method converts the collection of models with all nested relations into a QJsonDocument.

toMap()

The toMap method converts the collection of models with all nested relations into an attributes map QVector<QVariantMap>.

It returns an empty QVariantList for empty many type relations and a null QVariant for empty one type relations.

toMapVariantList()

The toMapVariantList method converts the collection of models with all nested relations into an attributes map, but it returns the QVariantList instead of the QVector<QVariantMap>.

It returns an empty QVariantList for empty many type relations and a null QVariant for empty one type relations.

note

The toMapVariantList method is internally needed by the toJson related methods.

toQuery()

The toQuery method returns the TinyBuilder instance containing a whereIn constraint with the collection of models' primary keys:

using Models::User;

ModelsCollection<User> users = User::whereEq("status", "VIP")->get();

users.toQuery()->update({
{"status", "Administrator"},
});

toVector()

The toVector method converts the collection of models with all nested relations into an attributes vector QVector<QVector<AttributeItem>>.

It returns an empty QVariantList for empty many type relations and a null QVariant for empty one type relations.

toVectorVariantList()

The toVectorVariantList method converts the collection of models with all nested relations into an attributes vector, but it returns the QVariantList instead of the QVector<QVector<AttributeItem>>.

It returns an empty QVariantList for empty many type relations and a null QVariant for empty one type relations.

note

The toVectorVariantList method is internally needed by the toJson related methods.

unique()

The unique method returns all of the unique models in the sorted collection. Any models with the same primary key as another model in the collection are removed:

ModelsCollection<User> users {
{{"id", 2}, {"name", "Kate"}},
{{"id", 1}, {"name", "Jack"}},
{{"id", 3}, {"name", "John"}},
{{"id", 1}, {"name", "Jack"}},
};

auto unique = users.unique();

/*
{
{{"id", 1}, {"name", "Jack"}},
{{"id", 2}, {"name", "Kate"}},
{{"id", 3}, {"name", "John"}},
}
*/

It sorts the collection internally because the ranges::unique can correctly operate only on the sorted container. You can disable it by passing false using the first sort parameter:

auto unique = users.sort().unique(false);

/*
{
{{"id", 1}, {"name", "Jack"}},
{{"id", 2}, {"name", "Kate"}},
{{"id", 3}, {"name", "John"}},
}
*/

uniqueBy()

The uniqueBy method returns all of the unique models in the sorted collection by the given column. Any models with the same column value as another model in the collection are removed. It needs the template argument, so it can cast the attribute value before comparing:

ModelsCollection<User> users {
{{"name", "Kate"}},
{{"name", "Jack"}},
{{"name", "John"}},
{{"name", "Jack"}},
};

auto unique = users.uniqueBy<QString>("name");

/*
{
{{"name", "Jack"}},
{{"name", "John"}},
{{"name", "Kate"}},
}
*/

It sorts the collection internally because the ranges::unique can correctly operate only on the sorted container. You can disable it by passing false using the second sort parameter:

auto unique = users.sortBy<QString>("name")
.uniqueBy<QString>("name", false);

/*
{
{{"name", "Jack"}},
{{"name", "John"}},
{{"name", "Kate"}},
}
*/

uniqueRelaxed()

The uniqueRelaxed method returns all of the unique models in the collection, it doesn't need a sorted collection. Any models with the same primary key as another model in the collection are removed:

ModelsCollection<User> users {
{{"id", 2}, {"name", "Kate"}},
{{"id", 1}, {"name", "Jack"}},
{{"id", 3}, {"name", "John"}},
{{"id", 1}, {"name", "Jack"}},
};

auto unique = users.uniqueRelaxed();

/*
{
{{"id", 2}, {"name", "Kate"}},
{{"id", 1}, {"name", "Jack"}},
{{"id", 3}, {"name", "John"}},
}
*/

uniqueRelaxedBy()

The uniqueRelaxedBy method returns all of the unique models in the collection by the given column, it doesn't need a sorted collection, but it needs the template argument, so it can cast the attribute value before comparing:

ModelsCollection<User> users {
{{"name", "Kate"}},
{{"name", "Jack"}},
{{"name", "John"}},
{{"name", "Jack"}},
};

auto unique = users.uniqueRelaxedBy<QString>("name");

/*
{
{{"name", "Kate"}},
{{"name", "Jack"}},
{{"name", "John"}},
}
*/

value()

The value method retrieves a given value from the first model of the collection:

ModelsCollection<User> users {
{{"name", "John"}, {"votes", 200}},
{{"name", "Jack"}, {"votes", 400}},
};

QVariant votes = users.value("votes");

// 200

Alternatively, you can cast an obtained QVariant value to the given type by the second value overload:

quint64 votes = users.value<quint64>("votes");

The value method also accepts the second defaultValue argument, which will be returned if a collection is empty, the first model is nullptr, or a model doesn't contain the given column:

auto votes = ModelsCollection<User>().value("votes", 0);

// 0

You can also call all value overloads provided by the QList::value.

where()

The where method filters the collection by a given column / value pair:

ModelsCollection<Product> products {
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 100}},
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Door"}, {"price", 100}},
};

auto filtered = products.where("price", "=", 100);

/*
{
{{"product", "Chair"}, {"price", 100}},
{{"product", "Door"}, {"price", 100}},
}
*/

For convenience, if you want to verify that a column is = to a given value, you may call whereEq method. Similar XxxEq methods are also defined for other commands:

auto filtered = products.whereEq("price", 100);

Optionally, you may pass a comparison operator as the second argument.
Supported operators are =, !=, <, >, <=, and >=:

ModelsCollection<Product> products {
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 100}},
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Door"}, {"price", 250}},
};

auto filtered = products.where("price", ">", 150);

/*
{
{{"product", "Desk"}, {"price", 200}},
{{"product", "Door"}, {"price", 250}},
}
*/

whereBetween()

The whereBetween method filters the collection by determining if a specified models' attribute value is within a given range:

ModelsCollection<Product> products {
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 80}},
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Pencil"}, {"price", 30}},
{{"product", "Door"}, {"price", 100}},
};

auto filtered = products.whereBetween<quint64>("price", {100, 200});

/*
{
{{"product", "Desk"}, {"price", 200}},
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Door"}, {"price", 100}},
}
*/

whereIn()

The whereIn method filters models from the collection that have a specified attribute value that is contained within the given unordered set:

ModelsCollection<Product> products {
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 100}},
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Door"}, {"price", 250}},
};

auto filtered = products.whereIn<quint64>("price", {100, 200});

/*
{
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 100}},
}
*/

An empty collection is returned if the values argument is empty whereIn("price", {}).

The order of models in the collection is preserved.

whereNotBetween()

The whereNotBetween method filters the collection by determining if a specified models' attribute value is outside of a given range:

ModelsCollection<Product> products {
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 80}},
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Pencil"}, {"price", 30}},
{{"product", "Door"}, {"price", 100}},
};

auto filtered = products.whereNotBetween<quint64>("price", {100, 200});

/*
{
{{"product", "Chair"}, {"price", 80}},
{{"product", "Pencil"}, {"price", 30}},
}
*/

whereNotIn()

The whereNotIn method removes models from the collection that have a specified attribute value that is contained within the given unordered set:

ModelsCollection<Product> products {
{{"product", "Desk"}, {"price", 200}},
{{"product", "Chair"}, {"price", 100}},
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Door"}, {"price", 250}},
};

auto filtered = products.whereNotIn<quint64>("price", {100, 200});

/*
{
{{"product", "Bookcase"}, {"price", 150}},
{{"product", "Door"}, {"price", 250}},
}
*/

All of the models are returned if the values argument is empty whereNotIn("price", {}).

The order of models in the collection is preserved.

whereNotNull()

The whereNotNull method returns models from the collection where the given column is not null QVariant:

#include <orm/utils/nullvariant.hpp>

using NullVariant = Orm::Utils::NullVariant;

ModelsCollection<User> users {
{{"name", "John"}},
{{"name", NullVariant::QString()}},
{{"name", "Jack"}},
};

auto filtered = users.whereNotNull("name");

/*
{
{{"name", "John"}},
{{"name", "Jack"}},
}
*/
note

The NullVariant class returns the correct null QVariant for both Qt 5 QVariant(QVariant::String) and also Qt 6 QVariant(QMetaType(QMetaType::QString)).

whereNull()

The whereNull method returns models from the collection where the given column is null QVariant:

#include <orm/utils/nullvariant.hpp>

using NullVariant = Orm::Utils::NullVariant;

ModelsCollection<User> users {
{{"name", "John"}},
{{"name", NullVariant::QString()}},
{{"name", "Jack"}},
};

auto filtered = users.whereNotNull("name");

// {{"name", NullVariant::QString()}}
note

The NullVariant class returns the correct null QVariant for both Qt 5 QVariant(QVariant::String) and also Qt 6 QVariant(QMetaType(QMetaType::QString)).

- + \ No newline at end of file diff --git a/tinyorm/getting-started.html b/tinyorm/getting-started.html index b37cbd0cf..06a807a00 100644 --- a/tinyorm/getting-started.html +++ b/tinyorm/getting-started.html @@ -14,13 +14,13 @@ - +

TinyORM: Getting Started

Introduction

TinyORM is an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using TinyORM, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, TinyORM models allow you to insert, update, and delete records from the table as well.

note

Before getting started, be sure to configure a database connection in your application. For more information on configuring your database, check out the database configuration documentation.

tip

If you want to see a model in which are used all possible TinyORM features you can look at the torrent.hpp in the TinyORM's tests, this Models::Torrent class serves also as a showcase, so all possible features are defined in it.

Generating Model Classes

To get started, let's create the simplest TinyORM model. Models typically live in the database\models directory and extend the Orm::Tiny::Model class. You may use the make:model command to generate a new model:

tom make:model User

If you would like to generate a database migration or seeder when you generate the model, you may use the --migration/-m or --seeder/-s options:

tom make:model User --migration --seeder

The --force option forces overwriting of existing files:

tom make:model User --migration --seeder --force

The make:model is king 👑 among scaffolding commands that you can use to generate complete TinyORM model classes, it supports all features that TinyORM models offer. All advanced features are described in the make:model help command:

tom make:model --help

Few examples:

# Setting some model attributes
tom make:model User --table=users --fillable=name,email,banned_at `
--guarded=password --dates=banned_at

# Generate relationship methods
tom make:model User --one-to-one=Passport `
--one-to-many=Post --foreign-key=post_id `
--one-to-many=Car

# Generate a basic many-to-many relationship
tom make:model User --belongs-to-many=Tag --with-timestamps

# Generate a many-to-many relationship
tom make:model User --belongs-to-many=Tag --foreign-key=tag_id `
--pivot-table=user_tag --as=tagged `
--with-pivot=active,soft --with-timestamps `
--pivot=Tagged

# Generate a pivot model
tom make:model Tagged --pivot-model
tom make:model Tagged --pivot-model --incrementing
tip

Writing a make:model commands is superb with the tab completion.

note

The --path and --realpath options work the same as for the make:migration command.

TinyORM Model Conventions

Let's examine a basic model class and discuss some of TinyORM's key conventions:

#pragma once
#ifndef FLIGHT_HPP
#define FLIGHT_HPP

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;

using Model::Model;
};

#endif // FLIGHT_HPP
tip

The TinyORM source tree contains the Torrent example model that also acts as the full-fledged example model. It has defined and also nicely commented all possible features that model classes can use or define.

Table Names

After glancing at the example above, you may have noticed that we did not tell TinyORM which database table corresponds to our Flight model. By convention, the "snake_case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, TinyORM will assume the Flight model stores records in the flights table, while an AirTrafficController model would store records in an air_traffic_controllers table.

If your model's corresponding database table does not fit this convention, you may manually specify the model's table name by defining the private u_table data member on the model:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! The table associated with the model. */
QString u_table {"flights"};
};

Primary Keys

TinyORM will also assume that each model's corresponding database table has a primary key column named id. If necessary, you may define a private u_primaryKey data member on your model to specify a different column that serves as your model's primary key:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! The primary key associated with the table. */
QString u_primaryKey {"id"};
};

In addition, TinyORM assumes that the primary key is an incrementing integer value. If you wish to use a non-incrementing or a non-numeric primary key you must define a private u_incrementing data member on your model that is set to false:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! Indicates if the model's ID is auto-incrementing. */
bool u_incrementing = false;
};
caution

Non-numeric primary keys are not currently implemented, u_incrementing code logic is fully implemented, but it is only one part to make it fully work.

"Composite" Primary Keys

TinyORM requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by TinyORM models. However, you are free to add additional multi-column unique indexes to your database tables, in addition to the table's uniquely identifying primary key.

Timestamps

By default, TinyORM expects created_at and updated_at columns to exist on your model's corresponding database table. TinyORM will automatically set these column's values when models are created or updated. If you do not want these columns to be automatically managed by TinyORM, you should define a private u_timestamps data member on your model with a value of false:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! Indicates if the model should be timestamped. */
bool u_timestamps = false;
};

The u_dates static data member controls the casting of timestamp attributes. The created_at and updated_at columns are automatically added to the u_dates string list when the u_timestamps is true. Also, the Soft Deleting feature adds the deleted_at column to the u_dates.

You may add additional columns to the u_dates list. After that, these columns will be automatically formatted using the format in the u_dateFormat data member during the setAttribute method call:

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! The attributes that should be mutated to dates. */
inline static const QStringList u_dates {"departure_at"};
};

If you need to customize the format of your model's timestamps, set the private u_dateFormat data member on your model. This data member determines how date attributes are stored in the database, supported formats are described in the QDateTime documentation:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! The storage format of the model's date columns. */
QString u_dateFormat {"yyyy-MM-dd HH:mm:ss"};
};

If you need to customize the format of your model's time columns, set the private u_timeFormat data member on your model. This data member determines how time attributes are stored in the database, supported formats are described in the QTime documentation. The default value for u_timeFormat is HH:mm:ss:

/*! The storage format of the model's time columns. */
QString u_timeFormat {"HH:mm:ss.zzz"};

The default value for datetime or timestamp columns is yyyy-MM-dd HH:mm:ss and for time columns is HH:mm:ss.

Unix timestamps

You can set the u_dateFormat to U if you want to store dates in the database as unix timestamps:

QString u_dateFormat {QLatin1Char('U')};

In this case all date attributes set in the u_dates will be handled as unix timestamps, so also the created_at and updated_at timestamp attributes.

To create unix timestamp columns using the tom migrations you should use integer types:

Schema::table("flights", [](Blueprint &table)
{
table.bigInteger("created_at").nullable();
table.bigInteger("updated_at").nullable();
});
Custom timestamp column names

If you need to customize the names of the columns used to store the timestamps, you may define CREATED_AT and UPDATED_AT private static getter methods on your model:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! The name of the "created at" column. */
static QString CREATED_AT() { return QStringLiteral("creation_date"); }
/*! The name of the "updated at" column. */
static QString UPDATED_AT() { return QStringLiteral("updated_date"); }
};

Touching timestamps

You can explicitly touch timestamps using the touch method defined on the Model:

auto flight = Flight::find(1);

flight->touch();
flight->touch("added_on"); // Custom column name

You can also touch multiple rows at once using the touch method defined on the TinyBuilder:

auto [affected, query] = Flight::whereEq("status", "new")->touch();

The touch method may also be called when building a relationship query:

flight->history()->touch();
flight->history()->whereEq("status", "new").touch();

Database Connections

By default, all TinyORM models will use the default database connection that is configured for your application. If you would like to specify a different connection that should be used when interacting with a particular model, you should define a u_connection private data member on the model:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! The database connection that should be used by the model. */
QString u_connection {"sqlite"};
};

In special cases, when you want to query the database through a different connection, you can use Model::on method, which takes the connection name as the first argument:

auto user = User::on("sqlite")->find(1);

Default Attribute Values

By default, a newly instantiated model instance will not contain any attribute values. If you would like to define the default values for some of your model's attributes, you may define an u_attributes data member on your model, it has to be static and can be const:

#include <QDateTime>

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;
using Model::Model;

private:
/*! The model's default values for attributes. */
inline static const QVector<AttributeItem> u_attributes {
{"delayed", false},
{"progress", 0},
{"added_on", QDateTime::currentDateTimeUtc()},
};
};
caution

Use the Model::instance or Model::instanceHeap related methods to instantiate a model that contains a QDateTime in Default Attribute Values, or if attributes you want to pass to the model's constructor contain a QDateTime instance (problem is described below).

QDateTime and connection name problem

If your Default Attribute Values or attributes that you can pass to the Model constructor contain the QDateTime instance, then TinyORM throws an exception. You have to use the Model::instance related methods to create such a Model.

Virtually everything important is covered in the thrown exception, but let me summarize it. The problem is that the QDateTime instance is converted to a string based on the Model::u_dateFormat, or if not defined, the date format from Orm::Query::Grammars::Grammar will be used. This QueryGrammar is obtained from Orm::DatabaseConnection and because of that TinyORM needs to know the connection name and that's the crux of this problem. You can define your connection name using the Model::u_connection in your derived model class, but this derived model is not yet initialized, so the Model::u_connection is also not initialized.

So if the Model::u_connection is not yet initialized, TinyORM can't obtain the Orm::DatabaseConnection -> QueryGrammar -> dateFormat.

Retrieving Models

Once you have created a model and its associated database table, you are ready to start retrieving data from your database. You can think of each TinyORM model as a powerful query builder allowing you to fluently query the database table associated with the model. The model's all method will retrieve all of the records from the model's associated database table:

#include <QDebug>

#include "models/flight.hpp"

for (const auto &flight : Flight::all())
qDebug() << flight["name"].toString();

Building Queries

The TinyORM all method will return all of the results in the model's table. However, since each TinyORM model serves as a query builder, you may add additional constraints to queries and then invoke the get method to retrieve the results:

auto flights = Flight::whereEq("active", 1)
->orderBy("name")
.take(10)
.get();
tip

Since TinyORM models are query builders, you should review all of the methods provided by TinyORM's query builder. You may use any of these methods when writing your TinyORM queries.

note

All the static methods defined on the Orm::Tiny::Model<Derived, AllRelations...> class, which start building queries like where, latest, oldest, with, ... return std::unique_ptr<TinyBuilder<Model>>, TinyBuilder = Orm::Tiny::Builder and Model template argument is queried model class.

Refreshing Models

If you already have an instance of the TinyORM model that was retrieved from the database, you can "refresh" the model using the fresh and refresh methods. The fresh method will re-retrieve the model from the database. The existing model instance will not be affected:

auto flight = Flight::whereEq("number", "FR 900")->first();

auto freshFlight = flight->fresh();

The refresh method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well:

auto flight = Flight::whereEq("number", "FR 900")->first();

flight->setAttribute("number", "FR 456");

flight->refresh();

flight->getAttribute("number"); // "FR 900"

Containers

As we have seen, TinyORM methods like all and get retrieve multiple records from the database. Since these methods return a QVector<Model>, you can iterate it like any other container with the Range-based for loop, STL-Style Iterators, Java-Style Iterators or Ranges.

#include <QDebug>

#include "models/flight.hpp"

for (const auto &flight : Flight::all())
qDebug() << flight["name"].toString();
note

An all method is defined on the Orm::Tiny::Model<Derived, AllRelations...> class and get method is defined on the Orm::Tiny::Builder, may be also referred as TinyBuilder, and on the Orm::Query::Builder alias QueryBuilder.

Chunking Results

Your application may run out of memory if you attempt to load tens of thousands of TinyORM records via the all or get methods. Instead of using these methods, the chunk method may be used to process large numbers of models more efficiently.

The chunk method will retrieve a subset of TinyORM models, passing them to a lambda expression for processing. Since only the current chunk of TinyORM models is retrieved at a time, the chunk method will provide significantly reduced memory usage when working with a large number of models:

Flight::chunk(200, [](QVector<Flight> &&flights, const int /*unused*/)
{
for (auto &&flight : flights) {
//
}

return true;
});

The first argument passed to the chunk method is the number of records you wish to receive per "chunk". The lambda expression passed as the second argument will be invoked for each chunk that is retrieved from the database. A database query will be executed to retrieve each chunk of records passed to the lambda expression.

If you are filtering the results of the chunk method based on a column that you will also be updating while iterating over the results, you should use the chunkById method. Using the chunk method in these scenarios could lead to unexpected and inconsistent results. Internally, the chunkById method will always retrieve models with an id column greater than the last model in the previous chunk:

Flight::whereEq("departed", true)
->chunkById(200, [](QVector<Flight> &&flights, const int /*unused*/)
{
for (auto &&flight : flights)
flight.update({{"departed", false}});

return true;
});

Advanced Subqueries

Subquery Selects

TinyORM also offers advanced subquery support, which allows you to pull information from related tables in a single query. For example, let's imagine that we have a table of flight destinations and a table of flights to destinations. The flights table contains an arrived_at column which indicates when the flight arrived at the destination.

Using the subquery functionality available to the query builder's select and addSelect methods, we can select all of the destinations and the name of the flight that most recently arrived at that destination using a single query:

#include "models/destination.hpp"
#include "models/flight.hpp"

return Destination::addSelect(
Flight::select("name")
->whereColumnEq("destination_id", "destinations.id")
.orderByDesc("arrived_at")
.limit(1)
.toBase(),
"last_flight")
->get();

Subquery Ordering

In addition, the query builder's orderBy function supports subqueries. Continuing to use our flight example, we may use this functionality to sort all destinations based on when the last flight arrived at that destination. Again, this may be done while executing a single database query:

return Destination::orderByDesc(
Flight::select("arrived_at")
->whereColumnEq("destination_id", "destinations.id")
.orderByDesc("arrived_at")
.limit(1)
.toBase())
->get();

Retrieving Single Models / Aggregates

In addition to retrieving all of the records matching a given query, you may also retrieve single records using the find, first, firstWhere, or firstWhereEq methods. Instead of returning a vector of models, these methods return a single model instance:

#include "models/flight.hpp"

// Retrieve a model by its primary key...
auto flight = Flight::find(1);

// Retrieve the first model matching the query constraints...
auto flight = Flight::whereEq("active", 1)->first();

// Alternative to retrieving the first model matching the query constraints...
auto flight = Flight::firstWhere("active", "=", 1);

// Alternative firstWhere method syntax
auto flight = Flight::firstWhereEq("active", 1);

Sometimes you may wish to perform some other action if no results are found. The findOr methods will return a single model instance or, if no results are found, execute the given lambda expression. The value returned by the lambda will be considered the result of the method:

auto flight = Flight::findOr(1, [] {
// ...
});

auto flight = Flight::findOr<int>(1, [] {
// ...
return 10;
});

auto flight = Flight::findOr<std::optional<Flight>>(1, [] {
// ...
return Flight::find(10);
});

To obtain only a subset of the model's attributes you may use the Model::only method, it returns the QVector<AttributeItem>:

#include "models/flight.hpp"

using Orm::Constants::ID;
using Orm::Constants::NAME;

auto flight = Flight::find(1);

auto attributes = flight->only({ID, NAME});

Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Orm::Tiny::ModelNotFoundError will be thrown:

auto flight = Flight::findOrFail(1);

auto flight = Flight::where("legs", ">", 3)->firstOrFail();

Retrieving Or Creating Models

The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first QVector<Orm::WhereItem> argument with the optional second QVector<Orm::AttributeItem> argument:

The firstOrNew method, like firstOrCreate, will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to manually call the save method to persist it:

#include "models/flight.hpp"

// Retrieve flight by name or create it if it doesn't exist...
auto flight = Flight::firstOrCreate({
{"name", "London to Paris"}
});

// Retrieve flight by name or create it with the name, delayed, and arrival_time attributes...
auto flight = Flight::firstOrCreate(
{{"name", "London to Paris"}},
{{"delayed", 1}, {"arrival_time", "11:30"}}
);

// Retrieve flight by name or instantiate a new Flight instance...
auto flight = Flight::firstOrNew({
{"name", "London to Paris"}
});

// Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes...
auto flight = Flight::firstOrNew(
{{"name", "Tokyo to Sydney"}},
{{"delayed", 1}, {"arrival_time", "11:30"}}
);

Retrieving Aggregates

When interacting with TinyORM models, you may also use the count, sum, max, and other aggregate methods provided by the query builder. As you might expect, these methods return a scalar value instead of a TinyORM model instance:

auto count = Flight::whereEq("active", 1)->count();

auto max = Flight::whereEq("active", 1)->max("price");

Inserting & Updating Models

Inserts

Of course, when using TinyORM, we don't only need to retrieve models from the database. We also need to insert new records. Thankfully, TinyORM makes it simple. To insert a new record into the database, you should instantiate a new model instance and set attributes on the model. Then, call the save method on the model instance:

#include "models/flight.hpp"

// Store a new flight in the database
Flight flight;
flight.setAttribute("name", "Slovakia to Czech");
flight.save();

In this example, we assign the name attribute of the Flight model instance. When we call the save method, a record will be inserted into the database. The model's created_at and updated_at timestamps will automatically be set when the save method is called, so there is no need to set them manually.

Alternatively, you may use the create method to "save" a new model using a single C++ statement. The inserted model instance will be returned to you by the create method:

#include "models/flight.hpp"

auto flight = Flight::create({
{"name", "London to Paris"},
});

However, before using the create method, you will need to specify either a u_fillable or u_guarded static data member on your model class. These static data members are required because all TinyORM models are protected against mass assignment vulnerabilities by default. To learn more about mass assignment, please consult the mass assignment documentation.

Updates

The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it and set any attributes you wish to update. Then, you should call the model's save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value:

#include "models/flight.hpp"

auto flight = Flight::find(1);

flight->setAttribute("name", "Paris to London");

flight->save();

Mass Updates

Updates can also be performed against models that match a given query. In this example, all flights that are active and have a destination of San Diego will be marked as delayed:

Flight::whereEq("active", 1)
->whereEq("destination", "San Diego")
.update({{"delayed", 1}});

The update method expects the QVector<Orm::UpdateItem> of column and value pairs representing the columns that should be updated.

Examining Attribute Changes

TinyORM provides the isDirty, isClean, and wasChanged methods to examine the internal state of your model and determine how its attributes have changed from when the model was originally retrieved.

The isDirty method determines if any of the model's attributes have been changed since the model was retrieved. You may pass a specific attribute name to the isDirty method to determine if a particular attribute is dirty. The isClean will determine if an attribute has remained unchanged since the model was retrieved. This method also accepts an optional attribute argument:

#include "models/user.hpp"

auto user = User::create({
{"first_name", "Silver"},
{"last_name", "Zachara"},
{"title", "Developer"},
});

user.setAttribute("title", "Painter");

user.isDirty(); // true
user.isDirty("title"); // true
user.isDirty("first_name"); // false

user.isClean(); // false
user.isClean("title"); // false
user.isClean("first_name"); // true

user.save();

user.isDirty(); // false
user.isClean(); // true

The wasChanged method determines if any attributes were changed after the model was last saved into the database. If needed, you may pass an attribute name to see if a particular attribute was changed:

auto user = User::create({
{"first_name", "Silver"},
{"last_name", "Zachara"},
{"title", "Developer"},
});

user.setAttribute("title", "Painter");

user.wasChanged(); // false

user.save();

user.wasChanged(); // true
user.wasChanged("title"); // true
user.wasChanged("first_name"); // false

Mass Assignment

You may use the create method to "save" a new model using a single C++ statement. The inserted model instance will be returned to you by the method:

#include "models/flight.hpp"

auto flight = Flight::create({
{"name", "London to Paris"},
});

However, before using the create method, you will need to specify either a u_fillable or u_guarded static data member on your model class. These data members are required because all TinyORM models are protected against mass assignment vulnerabilities by default.

A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed to your model's create method, allowing the user to escalate themselves to an administrator.

So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the u_fillable static data member on the model. For example, let's make the name attribute of our Flight model mass assignable:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;

using Model::Model;

/*! The attributes that are mass assignable. */
inline static QStringList u_fillable {
"name",
};
};

Once you have specified which attributes are mass assignable, you may use the create method to insert a new record in the database. The create method returns the newly created model instance:

auto flight = Flight::create({{"name", "London to Paris"}});

If you already have a model instance, you may use the fill method to populate it with the vector of attributes:

flight.fill({{"name", "Amsterdam to Frankfurt"}});

Allowing Mass Assignment

If you would like to make all of your attributes mass assignable, you may define your model's u_guarded static data member as an empty vector. If you choose to unguard your model, you should take special care to always hand-craft the vectors passed to TinyORM's fill, create, and update methods:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Flight final : public Model<Flight>
{
friend Model;

using Model::Model;

/*! The attributes that aren't mass assignable. */
inline static QStringList u_guarded {};
};

Upserts

Occasionally, you may need to update an existing model or create a new model if no matching model exists.

In the example below, if a flight exists with a departure location of Oakland and a destination location of San Diego, its price and discounted columns will be updated. If no such flight exists, a new flight will be created which has the attributes resulting from merging the first argument vector with the second argument vector:

auto flight = Flight::updateOrCreate(
{{"departure", "Oakland"}, {"destination", "San Diego"}},
{{"price", 99}, {"discounted", 1}}
);
note

The firstOrCreate and updateOrCreate methods persist the model, so there's no need to manually call the save method.

If you would like to perform multiple "upserts" in a single query, then you should use the upsert method instead. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is the vector of the columns that should be updated if a matching record already exists in the database. The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model:

Flight::upsert(
{{{"departure", "Oakland"}, {"destination", "San Diego"}, {"price", 99}},
{{"departure", "Chicago"}, {"destination", "New York"}, {"price", 150}}},
{"departure", "destination"},
{"price"}
);
caution

All databases except SQL Server require the columns in the second argument of the upsert method to have a "primary" or "unique" index. In addition, the MySQL database driver ignores the second argument of the upsert method and always uses the "primary" and "unique" indexes of the table to detect existing records.

info

Row and column aliases will be used with the MySQL server >=8.0.19 instead of the VALUES() function as is described in the MySQL documentation. The MySQL server version is auto-detected and can be overridden in the configuration.

Deleting Models

To delete a model, you may call the remove, or an alias deleteRow method on the model instance:

#include "models/flight.hpp"

auto flight = Flight::find(1);

flight->remove();

Deleting An Existing Model By Its Primary Key

In the example above, we are retrieving the model from the database before calling the remove method. However, if you know the primary key of the model, you may delete the model without explicitly retrieving it by calling the destroy method. In addition to accepting the single primary key, the destroy method can accept multiple primary keys:

Flight::destroy(1);

Flight::destroy({1, 2, 3});
note

The destroy method loads models from the database and calls the remove method on each model individually, the reason for this is future compatibility with events.

Deleting Models Using Queries

Of course, you may build the query to delete all models matching your query's criteria. In this example, we will delete all flights that are marked as inactive:

auto deletedRows = Flight::whereEq("active", 0)->remove();

Soft Deleting

In addition to actually removing records from your database, TinyORM can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model indicating the date and time at which the model was "deleted". To enable soft deletes for a model, add the Orm::Tiny::SoftDeletes base class to the model:

#include <orm/tiny/model.hpp>
#include <orm/tiny/softdeletes.hpp>

using Orm::Tiny::Model;
using Orm::Tiny::SoftDeletes;

class Flight final : public Model<Flight>,
public SoftDeletes<Flight>
{
friend Model;
using Model::Model;

private:
/*! The table associated with the model. */
QString u_table {"flights"};
};
info

The SoftDeletes base class will automatically cast the deleted_at attribute to the QDateTime instance for you (it adds the deleted_at column to the model's u_dates list).

You should also add the deleted_at column to your database table. The TinyORM schema builder contains a helper method to create this column:

Schema::table("flights", [](Blueprint &table)
{
table.softDeletes();
});

Schema::table("flights", [](Blueprint &table)
{
table.dropSoftDeletes();
});

Now, when you call the remove or deleteModel method on the model, the deleted_at column will be set to the current date and time. However, the model's database record will be left in the table. When querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.

To determine if a given model instance has been soft deleted, you may use the trashed method:

if (flight->trashed()) {
//
}

Restoring Soft Deleted Models

Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model, you may call the restore method on a model instance. The restore method will set the model's deleted_at column to null:

flight->restore();

You may also use the restore method in a query to restore multiple models:

Flight::withTrashed()
->whereEq("airline_id", 1)
.restore();

The restore method may also be used when building relationship queries:

flight->history()->restore();

Permanently Deleting Models

Sometimes you may need to truly remove a model from your database. You may use the forceDelete method (or it's alias forceRemove) to permanently remove a soft deleted model from the database table:

flight->forceDelete();

You may also use the forceDelete method when building TinyORM relationship queries:

flight->history()->forceDelete();

Querying Soft Deleted Models

Including Soft Deleted Models

As noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to be included in a query's results by calling the withTrashed method on the query:

auto flights = Flight::withTrashed()
->whereEq("account_id", 1)
.get();

The withTrashed method may also be called when building a relationship query:

flight->history()->withTrashed().get();

Retrieving Only Soft Deleted Models

The onlyTrashed method will retrieve only soft deleted models:

auto flights = Flight::onlyTrashed()
->whereEq("airline_id", 1)
.get();

The onlyTrashed method may also be called when building a relationship query:

flight->history()->onlyTrashed().get();

Excluding Soft Deleted Models

As noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to be excluded in a query's results by calling the withoutTrashed method on the query:

auto flights = Flight::withoutTrashed()
->whereEq("account_id", 1)
.get();

The withoutTrashed method may also be called when building a relationship query:

flight->history()->withoutTrashed().get();

Truncate Table

You may call the truncate method to delete all of the model's associated database records. The truncate operation will also reset any auto-incrementing IDs on the model's associated table:

Flight::truncate();

Replicating Models

You may create an unsaved copy of an existing model instance using the replicate method. This method is particularly useful when you have model instances that share many of the same attributes:

auto shipping = Address::create({
{"type", "shipping"},
{"line_1", "123 Example Street"},
{"city", "Victorville"},
{"state", "CA"},
{"postcode", "90001"},
});

auto billing = shipping.replicate();

billing.fill({
{"type", "billing"},
});

billing.save();

To exclude one or more attributes from being replicated to the new model, you may pass an unordered_set to the replicate method:

auto flight = Flight::create({
{"destination", "LAX"},
{"origin", "LHR"},
{"last_flown", "2020-03-04 11:00:00"},
{"last_pilot_id", 747},
});

flight = flight.replicate({
"last_flown",
"last_pilot_id",
});

Comparing Models

Sometimes you may need to determine if two models are the "same" or not. The is and isNot methods may be used to quickly verify two models have the same primary key, table, and database connection or not:

if (post->is(anotherPost)) {
//
}

if (post->isNot(anotherPost)) {
//
}

The is and isNot methods are also available when using the belongsTo and hasOne relationships. This method is particularly helpful when you would like to compare a related model without issuing a query to retrieve that model:

if (post->author()->is(user)) {
//
}
Equality comparison

The base Model class also defines the operator== that allows precisely comparing two models. It compares the content of all the model's data members, from all base classes to the most derived model class. The model1 == model2 expression guarantees that these two models are exactly the same.

It would be appropriate to mention that this comparison also includes relations, which means it will also compare all models (including their data members) these relations contain.

- + \ No newline at end of file diff --git a/tinyorm/relationships.html b/tinyorm/relationships.html index 9ae7d488d..4ccbd3e14 100644 --- a/tinyorm/relationships.html +++ b/tinyorm/relationships.html @@ -14,13 +14,13 @@ - +

TinyORM: Relationships

Introduction

Database tables are often related to one another. For example, a blog post may have many comments or an order could be related to the user who placed it. TinyORM makes managing and working with these relationships easy, and supports basic relationships:

Defining Relationships

TinyORM relationships are defined as methods on your TinyORM model classes. Since relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional query constraints on this posts relationship:

user->posts()->whereEq("active", 1).get();

But, before diving too deep into using relationships, let's learn how to define each type of relationship supported by TinyORM.

Common Rules

Before you start defining relationship methods, you have to declare a model class, let's examine following model class with a "one" type relation:

#pragma once
#ifndef USER_HPP
#define USER_HPP

#include <orm/tiny/model.hpp>

#include "models/phone.hpp"

using Orm::Tiny::Model;

class User final : public Model<User, Phone>
{
friend Model;
using Model::Model;

public:
/*! Get the phone associated with the user. */
std::unique_ptr<HasOne<User, Phone>>
phone()
{
return hasOne<Phone>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"phone", &User::phone); }},
};
};

#endif // USER_HPP

First, you have to extend the Model<Derived, AllRelations...>, it is a common class for all models, the first template parameter is the type-id of the defined model itself, this pattern is called a Curiously recurring template pattern pattern.

However, the second parameter is more interesting, here you have to provide a type-id of all related models. The TinyORM needs these types to store relationships in the hash.

Next, you have to define the u_relations hash, which maps relation names to relationship methods. 🔥🚀🙌

tip

You may omit the friend Model declaration and define all the private data and function members as public.

One To One

A one-to-one relationship is a very basic type of database relationship. For example, a User model might be associated with one Phone model. To define this relationship, we will place a phone method on the User model. The phone method should call the hasOne method and return its result. The hasOne<Related> method is available to your model via the model's Orm::Tiny::Model<Derived, AllRelations...> base class:

#pragma once
#ifndef USER_HPP
#define USER_HPP

#include <orm/tiny/model.hpp>

#include "models/phone.hpp"

using Orm::Tiny::Model;

class User final : public Model<User, Phone>
{
friend Model;
using Model::Model;

public:
/*! Get the phone associated with the user. */
std::unique_ptr<HasOne<User, Phone>>
phone()
{
return hasOne<Phone>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"phone", [](auto &v) { v(&User::phone); }},
};
};

#endif // USER_HPP

The Related template argument provided to the hasOne<Related> method is the type-id of the related model class. Once the relationship is defined, we may retrieve the related record using Model's getRelationValue<Related, Tag> method:

auto phone = User::find(1)->getRelationValue<Phone, Orm::One>("phone");

TinyORM determines the foreign key of the relationship based on the parent model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a first argument to the hasOne method:

return hasOne<Phone>("foreign_key");

Additionally, TinyORM assumes that the foreign key should have a value matching the primary key column of the parent. In other words, TinyORM will look for the value of the user's id column in the user_id column of the Phone record. If you would like the relationship to use a primary key value other than id or your model's u_primaryKey data member, you may pass a second argument to the hasOne method:

return hasOne<Phone>("foreign_key", "local_key");

Defining The Inverse Of The Relationship

So, we can access the Phone model from our User model. Next, let's define a relationship on the Phone model that will let us access the user that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo<Related> method:

#pragma once
#ifndef PHONE_HPP
#define PHONE_HPP

#include <orm/tiny/model.hpp>

#include "models/user.hpp"

using Orm::Tiny::Model;

class Phone final : public Model<Phone, User>
{
friend Model;
using Model::Model;

public:
/*! Get the user that owns the phone. */
std::unique_ptr<BelongsTo<Phone, User>>
user()
{
return belongsTo<User>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"user", [](auto &v) { v(&Phone::user); }},
};
};

#endif // PHONE_HPP

When invoking the user method, TinyORM will attempt to find a User model that has an id which matches the user_id column on the Phone model.

TinyORM determines the foreign key name by examining the type-name of the Related template parameter and suffixing the type-name with _id. So, in this case, TinyORM assumes that the Phone model has a user_id column.

However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the first argument to the belongsTo method:

/*! Get the user that owns the phone. */
std::unique_ptr<BelongsTo<Phone, User>>
user()
{
return belongsTo<User>("foreign_key");
}

If the parent model does not use id as its primary key, or you wish to find the associated model using a different column, you may pass a second argument to the belongsTo method specifying the parent table's custom key:

/*! Get the user that owns the phone. */
std::unique_ptr<BelongsTo<Phone, User>>
user()
{
return belongsTo<User>("foreign_key", "owner_key");
}

The third belongsTo parameter is the relation name, if you pass it, the foreign key name will be determined from it. By convention, TinyORM will "snakecase" this relation name and suffix it with a `followed by the name of the parent model's primary key column to generate foreign key, thefuncpredefined identifier is ideal for this. The relation name is also used in BelongsTo'sassociateanddisassociate` methods:

/*! Get the user that owns the phone. */
std::unique_ptr<BelongsTo<Phone, User>>
someUser()
{
return belongsTo<User>({}, {}, QString::fromUtf8(__func__)); // the foreign key will be some_user_id
}

The relation name will be guessed from the type-id of the Related template parameter, TinyORM takes this name and changes the first character to lower case, so in the example above, the relation name will be user.

One To Many

A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models. For example, a blog post may have an infinite number of comments. Like all other TinyORM relationships, one-to-many relationships are defined by defining a hasMany<Related> method on your TinyORM model:

#pragma once
#ifndef POST_HPP
#define POST_HPP

#include <orm/tiny/model.hpp>

#include "models/comment.hpp"

using Orm::Tiny::Model;

class Post final : public Model<Post, Comment>
{
friend Model;
using Model::Model;

public:
/*! Get the comments for the blog post. */
std::unique_ptr<HasMany<Post, Comment>>
comments()
{
return hasMany<Comment>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"comments", [](auto &v) { v(&Post::comments); }},
};
};

#endif // POST_HPP

Remember, TinyORM will automatically determine the proper foreign key column for the Comment model. By convention, TinyORM will take the "snake_case" name of the parent model and suffix it with _id. So, in this example, TinyORM will assume the foreign key column on the Comment model is post_id.

Once the relationship method has been defined, we can access the QVector<Related *> of related comments by Model's getRelationValue<Related, Container = QVector> method:

#include "models/post.hpp"

auto comments = Post::find(1)->getRelationValue<Comment>("comments");

for (auto *comment : comments) {
//
}

Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the comments method and continuing to chain conditions onto the query, all the TinyBuilder methods which are related to building queries are proxied:

auto comment = Post::find(1)->comments()
->whereEq("title", "foo")
.first();

Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method:

return hasMany<Comment>("foreign_key");

return hasMany<Comment>("foreign_key", "local_key");

One To Many (Inverse) / Belongs To

Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany relationship, define a relationship method on the child model which calls the belongsTo method:

#pragma once
#ifndef COMMENT_HPP
#define COMMENT_HPP

#include <orm/tiny/model.hpp>

#include "models/post.hpp"

using Orm::Tiny::Model;

class Comment final : public Model<Comment, Post>
{
friend Model;
using Model::Model;

public:
/*! Get the post that owns the comment. */
std::unique_ptr<BelongsTo<Comment, Post>>
post()
{
return belongsTo<Post>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"post", [](auto &v) { v(&Comment::post); }},
};
};

#endif // COMMENT_HPP

Once the relationship has been defined, we can retrieve a comment's parent post by Model's getRelationValue<Related, Tag> method:

#include "models/comment.hpp"

auto comment = Comment::find(1);

return comment->getRelationValue<Post, Orm::One>("post")->getAttribute<QString>("title");

In the example above, TinyORM will attempt to find a Post model that has an id which matches the post_id column on the Comment model.

TinyORM determines the foreign key name by examining the type-name of the Related template parameter and suffixing the type-name with a _ followed by the name of the parent model's primary key column. So, in this case, TinyORM assumes that the Post model's foreign key on the comments table is post_id.

However, if the foreign key for your relationship does not follow these conventions, you may pass a custom foreign key name as the first argument to the belongsTo method:

/*! Get the post that owns the comment. */
std::unique_ptr<BelongsTo<Comment, Post>>
post()
{
return belongsTo<Post>("foreign_key");
}

If your parent model does not use id as its primary key, or you wish to find the associated model using a different column, you may pass a second argument to the belongsTo method specifying your parent table's custom key:

/*! Get the post that owns the comment. */
std::unique_ptr<BelongsTo<Comment, Post>>
post()
{
return belongsTo<Post>("foreign_key", "owner_key");
}

The third belongsTo parameter is the relation name, if you pass it, the foreign key name will be determined from it. By convention, TinyORM will "snakecase" this relation name and suffix it with a `followed by the name of the parent model's primary key column to generate foreign key, thefuncpredefined identifier is ideal for this. The relation name is also used in BelongsTo'sassociateanddisassociate` methods:

/*! Get the post that owns the comment. */
std::unique_ptr<BelongsTo<Comment, Post>>
somePost()
{
return belongsTo<Post>({}, {}, QString::fromUtf8(__func__)); // the foreign key will be some_post_id
}

The relation name will be guessed from the type-id of the Related template parameter, TinyORM takes this name and changes the first character to lower case, so in the example above, the relation name will be user.

Default Models

The belongsTo, and hasOne relationships allow you to define a default model that will be returned if the given relationship is null. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user relation will return an empty User model if no user is attached to the Post model:

/*! Get the author of the post. */
std::unique_ptr<BelongsTo<Post, User>>
user()
{
// Ownership of a unique_ptr()
auto relation = belongsTo<User>();

relation->withDefault();

return relation;
}

To populate the default model with attributes, you may pass the vector of attributes to the withDefault method:

/*! Get the author of the post. */
std::unique_ptr<BelongsTo<Post, User>>
user()
{
// Ownership of a unique_ptr()
auto relation = belongsTo<User>();

relation->withDefault({{"name", "Guest Author"},
{"is_active", false}});

return relation;
}

Many To Many Relationships

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of a many-to-many relationship is a user that has many roles and those roles are also shared by other users in the application. For example, a user may be assigned the role of "Author" and "Editor"; however, those roles may also be assigned to other users as well. So, a user has many roles and a role has many users.

Table Structure

To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names and contains user_id and role_id columns. This table is used as an intermediate table linking the users and roles.

Remember, since a role can belong to many users, we cannot simply place a user_id column on the roles table. This would mean that a role could only belong to a single user. In order to provide support for roles being assigned to multiple users, the role_user table is needed. We can summarize the relationship's table structure like so:

users
id - integer
name - string

roles
id - integer
name - string

role_user
user_id - integer
role_id - integer

Model Structure

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method. The belongsToMany method is provided by the Orm::Tiny::Model<Derived, AllRelations...> base class that is used by all of your application's TinyORM models. For example, let's define a roles method on our User model. The first argument passed to this method is the name of the related model class:

#pragma once
#ifndef USER_HPP
#define USER_HPP

#include <orm/tiny/relations/pivot.hpp>

#include "models/role.hpp"

using Orm::Tiny::Model;
using Orm::Tiny::Relations::Pivot;

class User final : public Model<User, Role, Pivot>
{
friend Model;
using Model::Model;

public:
/*! The roles that belong to the user. */
std::unique_ptr<BelongsToMany<User, Role>>
roles()
{
return belongsToMany<Role>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"roles", [](auto &v) { v(&User::roles); }},
};
};

#endif // USER_HPP

Once the relationship is defined, you may access the user's roles as the QVector<Related *> by Model's getRelationValue<Related, Container = QVector> method:

#include <QDebug>

#include "models/user.hpp"

auto user = User::find(1);

for (auto *role : user->getRelationValue<Role>("roles"))
qDebug() << role->getAttribute<quint64>("id");

Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the roles method and continuing to chain conditions onto the query:

auto roles = User::find(1)->roles()->orderBy("name").get();

To determine the table name of the relationship's intermediate table, TinyORM will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a first argument to the belongsToMany method:

return belongsToMany<Role>("role_user");

In addition to customizing the name of the intermediate table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The second argument is the foreign key name of the model on which you are defining the relationship, while the third argument is the foreign key name of the model that you are joining to:

return belongsToMany<Role>("role_user", "user_id", "role_id");

The fourth and fifth arguments are primary key names on models in the many-to-many relation and the sixth argument is the relation name.

The relation name is used during Touching Parent Timestamps and will be guessed from the type-id of the Related template parameter, TinyORM takes this name, changes the first character to lower case, and appends s character. So in the example above, the relation name will be roles.

Defining The Inverse Of The Relationship

To define the "inverse" of a many-to-many relationship, you should define a method on the related model which also returns the result of the belongsToMany method. To complete our user / role example, let's define the users method on the Role model:

#pragma once
#ifndef ROLE_HPP
#define ROLE_HPP

#include <orm/tiny/relations/pivot.hpp>

using Orm::Tiny::Model;
using Orm::Tiny::Relations::Pivot;

class User; // Forward declaration to avoid cyclic dependency

class Role final : public Model<Role, User, Pivot>
{
friend Model;
using Model::Model;

public:
/*! The users that belong to the role. */
std::unique_ptr<BelongsToMany<Role, User>>
users()
{
return belongsToMany<User>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"users", [](auto &v) { v(&Role::users); }},
};
};

#endif // ROLE_HPP

As you can see, the relationship is defined exactly the same as its User model counterpart with the exception of referencing the User model. Since we're reusing the belongsToMany method, all of the usual table and key customization options are available when defining the "inverse" of many-to-many relationships.

Retrieving Intermediate Table Columns

As you have already learned, working with many-to-many relations requires the presence of an intermediate table. TinyORM provides some very helpful ways of interacting with this table. For example, let's assume our User model has many Role models that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:

#include <QDebug>

#include "models/user.hpp"

using Orm::Tiny::Relations::Pivot;

auto user = User::find(1);

for (auto *role : user->getRelationValue<Role>("roles"))
qDebug() << role->getRelation<Pivot, Orm::One>("pivot")
->getAttribute("created_at");

Notice that each Role model we retrieve has automatically assigned a pivot relationship. This relation contains a model representing the intermediate table and it is an instance of the Orm::Tiny::Relations::Pivot model class.

By default, only the model keys will be present on the pivot model. If your intermediate table contains extra attributes, you must specify them when defining the relationship:

// Ownership of a unique_ptr()
auto relation = belongsToMany<Role>();

relation->withPivot({"active", "created_by"});

return relation;

If you would like your intermediate table to have created_at and updated_at timestamps that are automatically maintained by TinyORM, call the withTimestamps method when defining the relationship:

// Ownership of a unique_ptr()
auto relation = belongsToMany<Role>();

relation->withTimestamps();

return relation;
caution

Intermediate tables that utilize TinyORM's automatically maintained timestamps are required to have both created_at and updated_at timestamp columns.

Customizing The pivot Relation Name

As noted previously, attributes from the intermediate table may be accessed on models via the pivot relation name. However, you are free to customize the name of this relation to better reflect its purpose within your application.

For example, if your application contains users that may subscribe to podcasts, you likely have a many-to-many relationship between users and podcasts. If this is the case, you may wish to rename your intermediate table relation name to subscription instead of pivot. This can be done using the as method when defining the relationship:

// Ownership of a unique_ptr()
auto relation = belongsToMany<Podcast>();

relation->as("subscription")
.withTimestamps();

return relation;

Once the custom intermediate table relation name has been specified, you may access the intermediate table data using the customized name:

#include <QDebug>

#include "models/user.hpp"

using Orm::Tiny::Relations::Pivot;

auto users = User::with("podcasts")->get();

for (auto &user : users)
for (auto *podcast : user.getRelation<Podcast>("podcasts"))
qDebug() << podcast->getRelation<Pivot, Orm::One>("subscription")
->getAttribute("created_at");

Defining Custom Intermediate Table Models

If you would like to define a custom model to represent the intermediate table of your many-to-many relationship, you may pass the custom pivot type as a second template argument to the belongsToMany<Related, PivotType = Pivot> method when defining the relationship. Custom pivot models give you the opportunity to define additional methods on the pivot model.

Custom many-to-many pivot models should extend the Orm::Tiny::Relations::BasePivot<PivotModel> class. For example, we may define a User model which uses a custom RoleUser pivot model:

#pragma once
#ifndef USER_HPP
#define USER_HPP

#include <orm/tiny/relations/pivot.hpp>

#include "models/role.hpp"

using Orm::Tiny::Model;
using Orm::Tiny::Relations::Pivot;

class User final : public Model<User, Role, Pivot>
{
friend Model;
using Model::Model;

public:
/*! The roles that belong to the user. */
std::unique_ptr<BelongsToMany<User, Role, RoleUser>>
roles()
{
return belongsToMany<Role, RoleUser>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"roles", [](auto &v) { v(&User::roles); }},
};
};

#endif // USER_HPP

When defining the RoleUser model, you should extend the Orm::Tiny::Relations::BasePivot<PivotModel> class:

#pragma once
#ifndef ROLEUSER_HPP
#define ROLEUSER_HPP

#include <orm/tiny/relations/basepivot.hpp>

using Orm::Tiny::Relations::BasePivot;

class RoleUser final : public BasePivot<RoleUser>
{
friend Model;
friend BasePivot;

using BasePivot::BasePivot;
};

#endif // ROLEUSER_HPP

You have to pass a custom pivot type to the AllRelations template parameter pack on Model<Derived, AllRelations...> so that the Model knows how to generate a std::variant, which holds all the relations and also you have to add a new mapping from the relation name to the custom pivot model type-id, this is described in more detail in the Common Rules:

#pragma once
#ifndef ROLE_HPP
#define ROLE_HPP

#include <orm/tiny/model.hpp>

#include "models/roleuser.hpp"

using Orm::Tiny::Model;

class User; // Forward declaration to avoid cyclic dependency

class Role final : public Model<Role, User, RoleUser>
{
friend Model;
using Model::Model;

public:
/*! The users that belong to the role. */
std::unique_ptr<BelongsToMany<Role, User>>
users()
{
return belongsToMany<User>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"users", [](auto &v) { v(&Role::users); }},
};
};

#endif // ROLE_HPP

Once the custom pivot model RoleUser has been defined, getRelation or getRelationValue method returns proper pivot type:

#include <QDebug>

#include "models/user.hpp"

auto users = User::with("roles")->get();

for (auto &user : users)
for (auto *role : user.getRelation<Role>("roles"))
qDebug() << role->getRelation<RoleUser, Orm::One>("pivot")
->getAttribute("created_at");
caution

Custom Pivot models may not use the SoftDeletes base class. If you need to soft delete pivot records consider converting your pivot model to an actual TinyORM model.

Custom Pivot Models And Incrementing IDs

If you have defined a many-to-many relationship that uses a custom pivot model, and that pivot model has an auto-incrementing primary key, you should ensure your custom pivot model class defines an u_incrementing data member that is set to true.

/*! Indicates if the IDs are auto-incrementing. */
bool u_incrementing = true;

Closer Look At Defining Custom Intermediate Table Models

I can tell that defining a custom intermediate table models is the most confusing part of the TinyORM framework, let's look closer at it.

If you are defining a custom RoleUser intermediate table for the Role model like in the example above then you have to pass the RoleUser pivot type as the second template argument to the User::roles() belongsToMany relationship method and you have to pass the RoleUser pivot type to the AllRelations template parameter pack on the Role model!

Do you see the confusing part? In short, if defining the User::roles() relation with the custom UserRole pivot model then add the UserRole type to the AllRelations template parameter pack on the Role model.

The same is true for the basic Pivot model, if you are using a basic pivot model and not a custom pivot model you still need to add the Pivot type to the AllRelations template parameter pack on the Model class!

The reason for all of this is that the Model knows how to generate and work with the std::variant that holds the pivot model in the Model::m_relations data member map, then you can get the pivot model using the Model::getRelationValue or Model::getRelation methods.

User Data Members on Custom Intermediate Table Models

This is another nonstandard part of the custom pivot models. The u_connection and u_timestamps user data members and the CREATED_AT() and UPDATED_AT() static getter methods are ignored when obtaining pivot records from the database during the lazy or eager loading.

Let's describe how these data members are resolved:

  • u_connection - inferred from the parent model
  • u_timestamps - true if obtained pivot attributes contain both the CREATED_AT and UPDATED_AT attributes
  • CREATED_AT, UPDATED_AT - inferred from the parent model, can be overridden using the withTimestamps() method

All these data members are taken into account normally when you call the create, save, update, ... on the Custom Pivot models!

Querying Relations

Since all TinyORM relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing a query to load the related models. In addition, all types of TinyORM relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL query against your database.

For example, imagine a blog application in which a User model has many associated Post models:

#include "models/post.hpp"

using Orm::Tiny::Model;

class User final : public Model<User, Post>
{
friend Model;
using Model::Model;

public:
/*! Get all of the posts for the user. */
std::unique_ptr<HasMany<User, Post>>
posts()
{
return hasMany<Post>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"posts", [](auto &v) { v(&User::posts); }},
};
};

You may query the posts relationship and add additional constraints to the relationship like so:

#include "models/user.hpp"

auto user = User::find(1);

user->posts()->whereEq("active", 1).get();

You are able to use any of the TinyORM query builder's methods on the relationship, so be sure to explore the query builder documentation to learn about all of the methods that are available to you.

note

All the TinyBuilder methods which are related to building queries are proxied on the Relation base class.

Chaining orWhere Clauses After Relationships

As demonstrated in the example above, you are free to add additional constraints to relationships when querying them. However, be careful when chaining orWhere clauses onto a relationship, as the orWhere clauses will be logically grouped at the same level as the relationship constraint:

user->posts()
->whereEq("active", 1)
.orWhere("votes", ">=", 100)
.get();

The example above will generate the following SQL. As you can see, the or clause instructs the query to return any user with greater than 100 votes. The query is no longer constrained to a specific user:

select *
from posts
where user_id = ? and active = 1 or votes >= 100

In most situations, you should use logical groups to group the conditional checks between parentheses:

user->posts()
->where([](auto &query)
{
query.whereEq("active", 1)
.orWhere("votes", ">=", 100);
})
.get();

The example above will produce the following SQL. Note that the logical grouping has properly grouped the constraints and the query remains constrained to a specific user:

select *
from posts
where user_id = ? and (active = 1 or votes >= 100)

Relationship Methods

If you do not need to add additional constraints to the TinyORM relationship query, you may access the relationship directly. For example, continuing to use our User and Post example models, we may access all of a user's posts like so:

#include "models/user.hpp"

auto user = User::find(1);

for (auto *post : user->getRelationValue<Post>("posts")) {
//
}

The getRelationValue<Related> method performs "lazy loading", meaning they will only load their relationship data when you actually access them. Because of this, developers often use eager loading to pre-load relationships they know will be accessed after loading the model. Eager loading provides a significant reduction in SQL queries that must be executed to load a model's relations.

To access eager loaded relationship use Model's getRelation<Related> method:

auto user = User::find(1);

for (auto *post : user->getRelation<Post>("posts")) {
//
}

As described above TinyORM offers two methods to access relationships; getRelation and getRelationValue.

The getRelation method is for "eager loaded" relations, when the relationship is not loaded, it throws the exception RelationNotLoadedError. The getRelationValue is for "lazy loading", when the relationship is not loaded, it will load it.

Both methods have two overloads, the getRelation<Related, Container = QVector> overload is for obtaining many type relationships:

auto posts = User::find(1)->getRelation<Post>("posts");

The getRelation<Related, Tag> overload is for obtaining "one" type relationships:

auto user = Post::find(1)->getRelation<User, Orm::One>("user");

The same is true for the getRelationValue method.

Querying Relationship Existence

When retrieving model records, you may wish to limit your results based on the existence of a relationship. For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the has and orHas methods:

#include "models/post.hpp"

// Retrieve all posts that have at least one comment...
auto posts = Post::has("comments")->get();

You may also specify an operator and count value to further customize the query:

// Retrieve all posts that have three or more comments...
auto posts = Post::has("comments", ">=", 3)->get();

Nested has statements may be constructed using "dot" notation. For example, you may retrieve all posts that have at least one comment that has at least one image:

// Retrieve posts that have at least one comment with images...
auto posts = Post::has<Image>("comments.images")->get();

If you need even more power, you may use the whereHas and orWhereHas methods to define additional query constraints on your has queries, such as inspecting the content of a comment:

// Retrieve posts with at least one comment containing words like code%...
auto posts = Post::whereHas("comments", [](auto &query)
{
query.where("content", LIKE, "code%");
})->get();

// Retrieve posts with at least ten comments containing words like code%...
auto posts = Post::whereHas("comments", [](auto &query)
{
query.where("content", LIKE, "code%");
}, ">=", 10)->get();
note

TinyORM does not currently support querying for relationship existence across databases. The relationships must exist within the same database.

All the has-related methods are templated by the Related template parameter, it looks something like the following has<Related>(..., const std::function<void(CallbackType<Related> &)> &callback = nullptr), you can pass a query callback to this methods and on the base of the Related template argument will be decided whether the Orm::QueryBuilder or Orm::TinyBuilder<Related> will be passed to the callback. As you can see this Related parameter exists because the Orm::TinyBuilder<Related> needs it.

The rule of thumbs are:

  • if you don't pass the Related template parameter or you pass void then the Orm::QueryBuilder & will be passed to the callback
  • if you pass it, then the Orm::TinyBuilder<Related> & will be passed to the callback
  • Related has to be of the same type as a relation name passed to the has-related method (a real type of the relation eg. type of the posts relation name is Post)
  • you have to always pass the Related template parameter for nested relations, you can not use nested relations with Related = void
  • in nested relations, where you can pass more relation names using "dot" notation, Related has to be of the same type as the last relation name passed to the has-related method like you can see in the nested example above or below

Querying Relationship Absence

When retrieving model records, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don't have any comments. To do so, you may pass the name of the relationship to the doesntHave and orDoesntHave methods:

#include "models/post.hpp"

auto posts = Post::doesntHave("comments")->get();

If you need even more power, you may use the whereDoesntHave and orWhereDoesntHave methods to add additional query constraints to your doesntHave queries, such as inspecting the content of a comment:

auto posts = Post::whereDoesntHave("comments", [](auto &query)
{
query.where("content", LIKE, "code%");
})->get();

You may use "dot" notation to execute a query against a nested relationship. For example, the following query will retrieve all posts that have comments from authors that are not banned:

auto posts = Post::whereDoesntHave<Author>("comments.author",
[](auto &query)
{
query.where("banned", false);
})->get();

Eager Loading

When accessing TinyORM relationships by Model's getRelationValue method, the related models are "lazy loaded". This means the relationship data is not actually loaded until you first access them. However, TinyORM can "eager load" relationships at the time you query the parent model. Eager loading alleviates the "N + 1" query problem. To illustrate the N + 1 query problem, consider a Book model that "belongs to" to an Author model:

using Orm::Tiny::Model;

class Book final : public Model<Book, Author>
{
friend Model;
using Model::Model;

public:
/*! Get the author that wrote the book. */
std::unique_ptr<BelongsTo<Book, Author>>
author()
{
return belongsTo<Author>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"author", [](auto &v) { v(&Book::author); }},
};
};

Now, let's retrieve all books and their authors:

#include <QDebug>

#include "models/book.hpp"

auto books = Book::all();

for (auto &book : books)
qDebug() << book.getRelationValue<Author, Orm::One>("author")
->getAttribute<QString>("name");

This loop will execute one query to retrieve all of the books within the database table, then another query for each book in order to retrieve the book's author. So, if we have 25 books, the code above would run 26 queries: one for the original book, and 25 additional queries to retrieve the author of each book.

Thankfully, we can use eager loading to reduce this operation to just two queries. When building a query, you may specify which relationships should be eager loaded using the with method:

auto books = Book::with("author")->get();

for (auto &book : books)
qDebug() << book.getRelation<Author, Orm::One>("author")
->getAttribute<QString>("name");

For this operation, only two queries will be executed - one query to retrieve all of the books and one query to retrieve all of the authors for all of the books:

select * from books

select * from authors where id in (1, 2, 3, 4, 5, ...)

Eager Loading Multiple Relationships

Sometimes you may need to eager load several different relationships. To do so, just pass a QVector<Orm::WithItem> of relationships to the with method:

auto books = Book::with({"author", "publisher"})->get();

Nested Eager Loading

To eager a relationship's relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts:

auto books = Book::with("author.contacts")->get();

Eager Loading Specific Columns

You may not always need every column from the relationships you are retrieving. For this reason, TinyORM allows you to specify which columns of the relationship you would like to retrieve:

auto books = Book::with("author:id,name,book_id")->get();
caution

When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve, otherwise relations will not be loaded correctly.

Eager Loading By Default

Sometimes you might want to always load some relationships when retrieving a model. To accomplish this, you may define a u_with data member on the model:

using Orm::Tiny::Model;

class Book final : public Model<Book, Author>
{
friend Model;
using Model::Model;

public:
/*! Get the author that wrote the book. */
std::unique_ptr<BelongsTo<Book, Author>>
author()
{
return belongsTo<Author>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"author", [](auto &v) { v(&Book::author); }},
};

/*! The relationships that should always be loaded. */
QVector<QString> u_with {
"author",
};
};

If you would like to remove an item from the u_with data member for a single query, you may use the without method:

auto books = Book::without("author")->get();

If you would like to override all items within the u_with data member for a single query, you may use the withOnly method:

auto books = Book::withOnly("genre")->get();

Constraining Eager Loads

Sometimes you may wish to eager load a relationship but also specify additional query conditions for the eager loading query. You can accomplish this by passing a QVector<Orm::WithItem> of relationships to the with method where the name data member of Orm::WithItem struct is a relationship name and the constraints data member expects a lambda expression that adds additional constraints to the eager loading query. The first argument passed to the constraints lambda expression is an underlying Orm::QueryBuilder for a related model:

#include "models/user.hpp"

auto users = User::with({{"posts", [](auto &query)
{
query.where("title", "like", "%code%");
}}})->get();

In this example, TinyORM will only eager load posts where the post's title column contains the word code. You may call other query builder methods to further customize the eager loading operation:

auto users = User::with({{"posts", [](auto &query)
{
query.orderBy("created_at", "desc");
}}})->get();
note

The limit and take query builder methods may not be used when constraining eager loads.

Lazy Eager Loading

Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models:

#include "models/book.hpp"

auto book = Book::find(1);

if (someCondition)
book->load("author");

You may load more relationships at once, to do so, just pass a QVector<Orm::WithItem> of relationships to the load method:

Book::find(1)->load({"author", "publisher"});
note

So far, this only works on models, not on containers returned from Model's get or all methods.

If you need to set additional query constraints on the eager loading query, you may pass a QVector<Orm::WithItem> of relationships to the load method where the name data member of Orm::WithItem struct is a relationship name and the constraints data member expects a lambda expression that adds additional constraints to the eager loading query. The first argument passed to the constraints lambda expression is an underlying Orm::QueryBuilder for a related model:

author->load({{"books", [](auto &query)
{
query.orderBy("published_date", "asc");
}}});
tip

You can also use eager constraining in the Model's fresh method.

The save Method

TinyORM provides convenient methods for adding new models to relationships. For example, perhaps you need to add a new comment to a post. Instead of manually setting the post_id attribute on the Comment model you may insert the comment using the relationship's save method:

#include "models/comment.hpp"
#include "models/post.hpp"

Comment comment({{"message", "A new comment."}});

auto post = Post::find(1);

post->comments()->save(comment);

Note that we did not access the comments relationship with the getRelation or getRelationValue method. Instead, we called the comments method to obtain an instance of the relationship. The save method will automatically add the appropriate post_id value to the new Comment model.

If you need to save multiple related models, you may use the saveMany method:

auto post = Post::find(1);

post->comments()->saveMany({
{{"message", "A new comment."}},
{{'message", "Another new comment."}},
});

The save and saveMany methods will not add the new models to any in-memory relationships that are already loaded onto the parent model. If you plan on accessing the relationship after using the save or saveMany methods, you may wish to use the refresh method to reload the model and its relationships:

post->comments()->save(comment);

post->refresh();

// All comments, including the newly saved comment...
post->getRelation<Comment>("comments");

The many-to-many relationship also supports the save and saveMany methods. In addition, you may pass the pivot attributes as a second argument and select if you want to touch parent timestamps as a third argument:

auto user = User::find(2);

Role role {{"name", "admin"}};

user->roles()->save(role, {{"active", true}});

Role role1 {{"name", "edit"}};
Role role2 {{"name", "view"}};

user->roles()->saveMany({role1, role2}, {{{"active", true}},
{{"active", false}}});

// No pivot attributes for role1
user->roles()->saveMany({role1, role2}, {{}, {{"active", false}}});

Recursively Saving Models & Relationships

If you would like to save your model and all of its associated relationships, you may use the push method. In this example, the Post model will be saved as well as its comments and the comment's authors:

auto post = Post::find(1);

post->getRelationValue<Comment>("comments").at(0)->setAttribute("message", "Message");

post->getRelationValue<Comment>("comments").first()
->getRelationValue<User, Orm::One>("author")->setAttribute("name", "Author Name");

post->push();

The create Method

In addition to the save and saveMany methods, you may also use the create method, which accepts a vector of attributes, creates a model, and inserts it into the database. The difference between save and create is that save accepts a full TinyORM model instance while create accepts a QVector<Orm::AttributeItem>. The newly created model will be returned by the create method:

#include "models/post.hpp"

auto post = Post::find(1);

auto comment = post->comments()->create({
{"message", "A new comment."},
});

You may use the createMany method to create multiple related models:

auto post = Post::find(1);

auto comments = post->comments()->createMany({
{{"message", "A new comment."}, {"is_published", true}},
{{"message", "Another new comment."}, {"is_published", false}},
});

The many-to-many relationship also supports the create and createMany methods. In addition, you may pass the pivot attributes as a second argument and select if you want to touch parent timestamps as a third argument:

auto user = User::find(2);

user->roles()->create({{"name", "admin"}}, {{"active", true}});

user->roles()->createMany({
{{"name", "edit"}},
{{"name", "view"}},
}, {
{{"active", true}},
{{"active", false}},
});

// No pivot attributes for the first role
user->roles()->createMany({
{{"name", "edit"}},
{{"name", "view"}},
}, {
{},
{{"active", false}},
});

You may also use the findOrNew, firstOrNew, firstOrCreate, and updateOrCreate methods to create and update models on relationships.

tip

Before using the create method, be sure to review the mass assignment documentation.

Belongs To Relationships

If you would like to assign a child model to a new parent model, you may use the associate method. In this example, the User model defines a belongsTo relationship to the Account model. The associate method will set the foreign key on the child model:

#include "models/user.hpp"

User user {{"name", "Mike"}};

auto account = Account::find(10);

user.account()->associate(*account);

user.save();

To remove a parent model from a child model, you may use the dissociate method. This method will set the relationship's foreign key to null:

user.account()->dissociate();

user.save();

Many To Many Relationships

Attaching / Detaching

TinyORM also provides methods to make working with many-to-many relationships more convenient. For example, let's imagine a user can have many roles and a role can have many users. You may use the attach method to attach a role to a user by inserting a record in the relationship's intermediate table:

#include "models/user.hpp"

auto user = User::find(1);

user->roles()->attach(roleId);

When attaching a relationship to a model, you may also pass a vector of additional data to be inserted into the intermediate table:

const auto expires = true;

user->roles()->attach(roleId, {{"expires", expires}});

Sometimes it may be necessary to remove a role from a user. To remove a many-to-many relationship record, use the detach method. The detach method will delete the appropriate record out of the intermediate table; however, both models will remain in the database:

// Detach a single role from the user...
user->roles()->detach(roleId);

// Detach all roles from the user...
user->roles()->detachAll();

For convenience, attach and detach also accept vectors of IDs or Model instances as input:

auto user = User::find(1);

user->roles()->detach({1, 2, 3});

Role role1({{"name", "Role 1"}});
role1.save();
Role role2({{"name", "Role 2"}});
role2.save();

user->roles()->attach({{role1}, {role2}});

The attach method also accepts std::map as input, so you can pass different attributes for each model you are attaching:

user->roles()->attach({
{1, {{"expires", true}, {"is_active", false}}},
{2, {{"expires", false}, {"is_active", true}}},
});

Syncing Associations

You may also use the sync method to construct many-to-many associations. The sync method accepts a vector of IDs to place on the intermediate table. Any IDs that are not in the given vector will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given vector will exist in the intermediate table:

user->roles()->sync({1, 2, 3});

You may also pass additional intermediate table values with the IDs:

user->roles()->sync({
{1, {{"expires", true}}},
{2, {}},
{3, {}},
});

If you do not want to detach existing IDs that are missing from the given vector, you may use the syncWithoutDetaching method:

user->roles()->syncWithoutDetaching({1, 2, 3});

Updating A Record On The Intermediate Table

If you need to update an existing row in your relationship's intermediate table, you may use the updateExistingPivot method. This method accepts the intermediate record foreign key and the vector of attributes to update:

auto user = User::find(1);

user->roles()->updateExistingPivot(roleId, {
{"active", false},
});

Touching Parent Timestamps

When a model defines a belongsTo relationship to another model, such as a Comment which belongs to a Post, it is sometimes helpful to update the parent's timestamp when the child model is updated.

For example, when a Comment model is updated, you may want to automatically "touch" the updated_at timestamp of the owning Post so that it is set to the current date and time. To accomplish this, you may add a u_touches data member to your child model containing the names of the relationships that should have their updated_at timestamps updated when the child model is updated:

using Orm::Tiny::Model;

class Comment final : public Model<Comment, Post>
{
friend Model;
using Model::Model;

public:
/*! Get the post that owns the comment. */
std::unique_ptr<BelongsTo<Comment, Post>>
post()
{
return belongsTo<Post>();
}

private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"post", [](auto &v) { v(&Comment::post); }},
};

/*! All of the relationships to be touched. */
QStringList u_touches {"post"};
};
note

Parent model timestamps will only be updated if the child model is updated using TinyORM's save, push, or remove method.

- + \ No newline at end of file diff --git a/tinyorm/serialization.html b/tinyorm/serialization.html index 241ecd880..65ac37692 100644 --- a/tinyorm/serialization.html +++ b/tinyorm/serialization.html @@ -14,13 +14,13 @@ - +

TinyORM: Serialization

Introduction

When building APIs using TinyORM, you will often need to convert your models and relationships to vectors, maps, or JSON. TinyORM includes convenient methods for making these conversions, as well as controlling which attributes are included in the serialized representation of your models.

Serializing Models & Collections

Serializing To Vectors & Maps

To convert a model and its loaded relationships to a vector, you should use the toVector or toMap methods. This methods are recursive, so all attributes and all relations (including the relations of relations) will be converted to vectors:

using Models::User;

auto user = User::with("roles")->first();

return user->toVector();

return user->toMap();

The attributesToVector or attributesToMap methods may be used to convert a model's attributes to a vector or map but not its relationships:

auto user = User::first();

return user->attributesToVector();

return user->attributesToMap();

You may also convert entire collections of models to vectors or maps by calling the toVector or toMap methods on the collection instance:

ModelsCollection<User> users = User::with("roles")->all();

return users.toVector();

return users.toMap();

Serializing To JSON

To convert a model to JSON, you should use the toJson method. Like toVector or toMap, the toJson method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are supported by QJsonDocument::toJson:

using Models::User;

auto user = User::with("roles")->find(1);

return user->toJson();

return user->toJson(QJsonDocument::Indented);

You may also convert entire collections of models to JSON by calling the toJson method on the collection instance:

ModelsCollection<User> users = User::with("roles")->findMany({1, 2});

return users.toJson();

You can also convert models to the QJsonObject and QJsonDocument using the toJsonArray and toJsonDocument methods and collection of models to QJsonArray and QJsonDocument using the toJsonArray and toJsonDocument methods.

Relationships

When a TinyORM model is converted to JSON, its loaded relationships will automatically be included as attributes on the JSON object. Also, though TinyORM relationship methods are defined using "camelCase" method names, a relationship's JSON attributes will be "snake_case".

This behavior is affected and can be overridden by the u_snakeAttributes static data member:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class Album final : public Model<Album, AlbumImage>
{
friend Model;
using Model::Model;

/*! Indicates whether attributes are snake_cased during serialization. */
inline static const bool u_snakeAttributes = false;
};

Hiding Attributes From JSON

Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's vector, map, or JSON representation. To do so, add a u_hidden static data member to your model. Attributes that are listed in the u_hidden data member set will not be included in the serialized representation of your model:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class User final : public Model<User>
{
friend Model;
using Model::Model;

/*! The attributes that should be hidden during serialization. */
inline static std::set<QString> u_hidden {"password"};
};
note

To hide relationships, add the relationship's method name to your TinyORM model's u_hidden static data member.

Alternatively, you may use the u_visible static data member to define an "allow list" of attributes that should be included in your model's vector, map, and JSON representation. All attributes that are not present in the u_visible set will be hidden during serialization:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class User final : public Model<User>
{
friend Model;
using Model::Model;

/*! The attributes that should be visible during serialization. */
inline static std::set<QString> u_visible {
"first_name", "last_name",
};
};

Temporarily Modifying Attribute Visibility

If you would like to make some typically hidden attributes visible on a given model instance, you may use the makeVisible method. The makeVisible method returns a model reference:

return user.makeVisible("attribute").toMap();

return user.makeVisible({"id", "name"}).toMap();

Likewise, if you would like to hide some attributes that are typically visible, you may use the makeHidden method.

return user.makeHidden("attribute").toVector();

return user.makeHidden({"id", "name"}).toVector();

If you wish to temporarily override all of the visible or hidden attributes, you may use the setVisible and setHidden methods respectively:

return user.setVisible({"id", "name"}).toMap();

return user.setHidden({"email", "password", "note"}).toJson();

You can also clear all visible and hidden attributes or determine whether a visible / hidden attribute is defined:

user.clearVisible();

user.clearHidden();

return user.hasVisible("name");

return user.hasHidden("password");

Appending Values To JSON

Occasionally, when converting models to vector, map, or JSON, you may wish to add attributes that do not have a corresponding column in your database. To do so, first define an accessor for the value:

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class User final : public Model<User>
{
friend Model;
using Model::Model;

protected:
/*! Accessor to determine if the user is an administrator. */
Attribute isAdmin() const noexcept
{
return Attribute::make(/* get */ []() -> QVariant
{
return QStringLiteral("yes");
});
}
};

If you would like the accessor to always be appended to your model's vector, map, and JSON representations, you may add the attribute name to the u_appends data member set of your model. Note that attribute names are typically referenced using their "snake_case" serialized representation, even though the accessor's method name is defined using "camelCase":

#include <orm/tiny/model.hpp>

using Orm::Tiny::Model;

class User final : public Model<User>
{
friend Model;
using Model::Model;

/*! Map of mutator names to methods. */
inline static const QHash<QString, MutatorFunction> u_mutators {
{"is_admin", &User::isAdmin},
};

/*! The attributes that should be appended during serialization. */
std::set<QString> u_appends {"is_admin"};
};

Once the attribute has been added to the u_appends set, it will be included in both the model's vector, map, and JSON representations. Attributes in the u_appends set will also respect the u_visible and u_hidden attribute settings configured on the model.

Special note should be given to the u_mutators static data member map, which maps accessors' attribute names to its methods. This data member is required because C++ does not currently support reflection.

Appending At Run Time

At runtime, you may instruct a model instance to append additional attributes using the append method. Or, you may use the setAppends method to override the entire set of appended attributes for a given model instance:

return user.append("is_admin").toVector();

return user.append({"is_admin", "is_banned"}).toMap();

return user.setAppends({"is_admin"}).toJson();

And you can also clear all appends or determine whether an append is defined:

user.clearAppends();

return user.hasAppend("is_admin");

Date Serialization

Customizing The Default Date Format

You may customize the default serialization format by overriding the serializeDate and serializeDateTime methods. These methods do not affect how your dates are formatted for storage in the database:

/*! Prepare a date for vector, map, or JSON serialization. */
QString serializeDate(const QDate date)
{
return date.toString("yyyy-MM-dd");
}

/*! Prepare a datetime for vector, map, or JSON serialization. */
QString serializeDateTime(const QDateTime &datetime)
{
return datetime.toUTC().toString("yyyy-MM-ddTHH:mm:ssZ");
}

Customizing The Date Format Per Attribute

You may customize the serialization format of individual TinyORM date attributes by specifying the date format in the model's cast declarations:

/*! The attributes that should be cast. */
inline static std::unordered_map<QString, CastItem> u_casts {
{"birthday", {CastType::CustomQDate, "yyyy-MM-dd"}},
{"joined_at", {CastType::CustomQDateTime, "yyyy-MM-dd HH:00"}},
};
- + \ No newline at end of file