Databases With SQLModel (Connection, Lifespan Events, And Models) - FastAPI Beyond CRUD (Part 5)
By Ssali Jonathan
Summary
Topics Covered
- ORMs Perform All SQL Behind The Scenes
- SQLModel Merges Pydantic Validation With SQLAlchemy
- Yield Splits Lifespan Code Into Startup And Shutdown
- SQLModel Metadata Auto-Creates Database Tables At Startup
Full Transcript
what's up everyone welcome back so in this video we going to be making our application to adapt to our persistent database in the previous video we looked at how we could build a simple
functional CED API using an inmemory database and that database was represented by python list in real world applications it is very essential that
we use a persistent database solution now F API supports various types of databases if you want to use a relational database or if you want to use a and relational database the choice
is yours for this series we're going to be focusing on using a relational database specifically pql poql is a widely used free and open-source relational database management system
that comes with a lot of benefits of which if I began describing them in this video we will be wasting a lot of time while is in procress we also need an
object relational MPP which is just a way for us to interact with a database using our p programming language an object relational Mapp is
simply a translator between our programming language which is python in this case and the database that is relational database such as poql MySQL
SQ and so on ANM works in the following way it Maps objects to tables when you create a python class that python class is going
to represent a certain table in our database and each object create of that class is going to correspond to a row or a record of data within our database
secondly it interacts with a data for example whenever you create an object of a class that is Created from ANM we can interact with this as a python object
and we can call things such as methods and Define attributes on that specific object just like we're going to see behind the scenes ANM also performs
operations on objects like saving them deleting them updating them just like we did for the C these omm operations are translated into the
appropriate SQL queries that the database understand so whenever we use an omm and Carry Out crad in the background the omm is performing all the
necessary SQL without us having to worry about it the orm also handles converting python data types into database specific types and ver versa so for example if we
are having dat time objects in Python those datetime objects will be converted into dat time objects that the database
is going to understand and so on SQL Alchemy is the most popular omm solution for python that helps us to map objects
to tables and it also provides an hql toolkit that allows us to write high level python to represent SQL
statements however despite the fact that SQL Alchemy is powerful using it with f API is going to be complex and there is
where SQL model comes into the picture SQL model is ANM that enables us to use the PA of SQL Alchemy as well as the par
of pantic so much as we may write our models in a in a class object oriented manner those models are also identic models and therefore they can be used
for both data validation as well as our database operations now this project was also created by the creator of first API
and meaning that this was motivated by someone who saw the need to have SQL Alchemy integrated into pantic to create
the best orm for first API now without further Ado let us get into setting up our SQL model and looking at how we can use it for our database solution now in
conclusion NM is going to simplify the interactions by letting us developers use Python instead of SQL the first thing we're going to do is to first of all set up a database that you're going
to be working with we have chosen PR SQL and depending on which system you're using the process of installing poql is going to be different and it's going to involve a number of steps I already have
poql installed on my machine but I'm going to be showing you one of the ways in which you can get a free PR SQL database I'm not sponsored in this video
but this can help you to get a free PR SQL database that can help you work with PR SQL just in case you need it and that's where neon comes in so when you
go to the neon website you can create an account and right here NE neon console all you need to do is just create a project so we shall call This bookly And once you've been able to do that shall
create a database name and this is going to be our bookly DB now I'm not going to be using this I'm just showing you how to set it up so shall go ahead and create a project and once you've created
the project you're just simply going to go ahead and get a database URL that you can simply copy into your settings and then you'll be able to use that but for
my case I'm going to be using poql on my local machine so to do that I'm going to run the psql shell and right in there I
can access it via the user and once I've been able to access MySQL shell I'm going to go ahead and simply create a database so to create a database I'm going to go ahead and say
create database this is a simple SQL statement and then just simply going to call it bookly underscore DB and that will just
be able to create the database now for us to formulate the SQL or the post SQL URL to this database all I'm going to do is to go right inside our code right
here and I'm going to introduce a new file and I'm going to call that file EnV so EnV is going to be the file in which we going to create all settings
for our project these settings are going to be kept secret and are not going to be kept in our Version Control and this is going to be important in a way that in case we are to share this project
with other people or in case this code is to be accessed by anyone they will not be able to get these secret such as our database keys or our secret keys and so on so to begin I'm going to create a
file and I'll call ITV mind that I've kept it in the root project folder right here another thing I'm going to do is to go ahead and set
up an environment variable to stand to the URL of our poql now in your case it's going to be this neon URL right here but for my case it's going to be
something on local host another thing I'm going to be doing is to use an async DB API so I'm going to be using po SQL
with an asynchronous DB driver or DB API so DB API is just one way in which python allows us to access our database
so let us Begin by installing that DB driver so I'm going to go to our python right here or our terminal in my virtual environment and I'll begin by installing
it with Pip install and this is going to be our async PG once we've installed the sync PG now let's go ahead and formulate our PR SQL
URL so I'm going to create a database URL environment variable and this is going to be database URL now remember we are working
on local host for my case but you you already have one you've got from neon so what I'm going to do is to formulate this as I'm going to start by mentioning the kind of database that we're going to
be using which is going to be our postgressql plus the DB API or the driver that you're going to be using so in this case
we are going to be using our sync PG and then we shall need the user of that specific database so my user is going to be j35 and then the password of that user
now this is not going to be your password so please use your own password so I'm going to provide my password right here and once I provided my
password then the host is going to be Local Host and the port is going to be 54
32 then slash the name of the database which we have called bookly DB so once that is done and you've got your poql url then the next thing is going to be
for us to access this so that we can use it within our code so there are very many ways in which you can manage environment variables but to be specific
to fast API we shall use pantic settings which is just a tool or a library built on top of pantic to give us the ability to manage our environment variables so
to do that I'm going to go right in here in our terminal and then I'll say pep install
pantic Dash settings so this will collect identic settings and install it within our virtual environment so I want to um going to go ahead and set it up so
that we can read our environment variables so to begin we're going to go within our source folder right here and we're going to create a new file at the root of that folder we're going to call
that module config.py inside config we are going to
config.py inside config we are going to create the class that's going to be responsible for allowing us to read our environment variables and for us to do that we are going to make use of a
special class from p identic settings and that is going to be our base settings class so to begin we're going to import that we're going
to say from pantic settings we are going to get access to the settings class or the best settings class sorry for that and once we've been able to do that then
let's create our class and this class is going to be called our settings class this class is going to inherit from our base settings and once you've
been able to do that all we shall have to do is to just go ahead and get the exact key as we've written it in
here and then have it as the attribute of this class so what this will do is to automatically go ahead and read each key we've defined here and then have its
value accessed via this class just like we're going to look at it so right after doing that then the next thing is going to be for us to specify the right
type of that specific value of that specific key now for us to do that we're going to go ahead and specify that this is going to be a string so this is just
enough for us to read our database URL but the problem is we haven't H told pantic settings where it's going to get these settings from to do that we're going to be making use of another class
which is called a settings config dict or the settings config dictionary so we're going to go ahead and import that so I'll come right here and say import
the settings config dict now to influence any pantic model because this is actually a pantic model that we have right here we always going to make use
of the model config attribute so every class that is a p identic model is going to have a model config attribute and this is going to be a dictionary that will allow us to change the
configurations of a specific pantic model now for us to do that we're going to set it value to our settings config dict and in this case this settings
config dict is going to be helping us to point to where our EnV file is where to read our settings from so even if we go right in here we can look at some of the
attributes it has it has the EnV prefix in case you have an EnV prefix you can specify one right here just in case you have an EnV file you're reading from you will go ahead and do that from here if
you're reading from let's say a Json file a yo file it does all of that but for our case we're going to be using an EnV file we can also specify an EnV
encoding in case we are to have one but we're going to just keep it simple one other important attribute we're going to provide here is the extra attribute and in this case we're going to be ignoring
any extra attributes that will be read from our class so to do that we're going to go in here and the first thing we're going to do is to specify that ourv file
is going to be equal to Dot en EnV so this will go ahead and read the EnV file that we've created and provided our
database URL in so let us go ahead and do another setting so once we've been able to do that then let's go ahead and also add one extra attribute which is
going to be our extra so in this case we have extra equals to ignore so we can allow reading other extra attribute we can forbid them but we're going to
specify that we are going to ignore any extra attributes from from being R so we shall Define every key that shall get from our EnV file into our class so that
we can access it within our application so let us go ahead and test the working of this settings class now what I'm going to do is to go ahead and open up
my terminal so I come right here and say Python 3 and once I've been able to do that let me make this a little bigger so that you guys can see we're going to
begin by accessing this class with we've got right here so we're going to say from source. config CU that's where
from source. config CU that's where we've created the settings class shall go ahead and import our settings class and once we've been able to import that settings class we're going to
create an object to that class so let's just call it s and that is going to be our settings object so once we've been able to access
our settings object let us try to access our environment variable from this object so we shall say database URL just like we called it right here
and once you do that then we can successfully access that specific environment variable from our EnV file now keep in mind that this is a file
that we're not going to share with anyone we're going to add it to theg ignore file so that we do not commit it to Version Control so I'll just do that
right here I'll say e n V so that whenever we add this code to our gate repository that file is not tracked now away from
that once that is done now let us look at how we can connect to our database using our SQL model so to begin let us
go ahead and install SQL model so I'm going to exit this shell and then I'll close this so I'll begin by installing
SQL model with Pip install and then SQL model so this will go ahead and collect SQL model added to our virtual
environment so just like you see it depends on SQL Alchemy and also SQL model it depends on also pantic and yeah that's how we've been able to install
our SQL model so once you've been able to install SQL model let us go in our source folder and create a new package so this is going to be called our DB and
this is also going to be a python package just like we have the other packages so Insight here is where we're going to do everything that's specific
to our database by that I mean anything concerned with our creating sessions and also helping us to connect to our database all that code is going to be formed within this package now let us go
ahead and create a new file and that file is going to be main.py so inside main.py is where we
main.py so inside main.py is where we going to create our engine object now if you back with SQL alemy you will know that an engine is the basis on which you
do everything from connecting to your database to carrying out any sort of CR so SQL model also relies on that because it's based on SQL Alchemy therefore we
need to First create an engine now keep in mind that we are using an async DB API and therefore we need toate create
an async engine so let us look at how we do that so I'm going to go ahead and UT the create engine function from SQL model now these are all boarded from SQL
Alem therefore I'll just come and say from SQL model we are going to go ahead and access the create engine function but this is going to be creating an
async engine so for us to create the async engine why not use the async engine class from SQL so we're going to begin by importing
that so we shall say from SQL alchemex do async IO we shall go ahead
and import our async engine class so let us go ahead and create our engine so our engine is going to be
equal to create engine and this is going to take in our database URL and other attributes so let's go ahead and create that
settings object so I'm just simp going to come right here I'll create a config object now keep in mind that I've kept it like config just for syntax you can call it whatever you want but as long as
you're going to remember what you've called it now I'm just simply going to say this is going to be settings and to be an object of type settings so it's
going to be an object of our settings class now we're going to be importing this every time we shall need to access an environment variable so whenever you create an environment variable you go
ahead and add it within your EnV file and once you've added it there then you'll add it as a field to the config class and then after adding it as a config class then you access it via the
config object that we've created right here so let's go ahead and access that object so I begin by importing it I'll say from Source do config we are going
to go ahead and import our config object now let go ahead and set up our URL so our URL in this case is going to be our config object and once you've been able
to do that now also going set equal to true now remember when when using the create engine function the echo attribute is what allows us to see all the SQL that will be logged on every
transaction that we carry out in our database so I'll come right here and say Echo is going to be equal to two and just like that we've created the
basic engine object now to make this an async engine object we're going to begin by first of all making it an instance of
the async engine class so for us to begin I'm going to go ahead and just simply sorry for this so just going to come right here actually I made a
mistake here this supposed to be the database URL so I'll say config database URL and that will mark it as a database
URL now let me go ahead and also change this from our basic engine object to an async object so I'll just simply create an async engine object and then I'll
simply provide our engine so this will create it as our async engine all right with that out of the way now let us look
at how we can connect to our database now when is the right time to connect to a database the right time to connect to a database is when the application is starting
so how can we make a task run at the start of our application fpi allows us to do this in
an in a very interesting way and this is through life span events so lifespan event is something that you may want to run through the lifespan of
an application now this may involve something that you may not want to do or load during the lifetime of an application an example can be running a machine
learning model this can be something that can be expensive something that you cannot run at the start of your application however it may make more sense for you to start running your
machine learning application just at the start of your app and whenever that application is running that AI model or whatever you're running is going to be
running so let us look at how we can set that up to begin we're going to go to where I created that fast API instance
and we shall go ahead and simply set that functionality to work now is our server running yeah our server is running right here so I think I'll go
ahead and stop it with control and c and then I'll close the terminal that we have right here so each first instance is going to come with a special attribute called the Life Span attribute
and that is going to take in the code that you want to run at the start and at the stopping of our server so let
us create our first lifespan event to create a lifespan event we are going to be making use of a specific decorator
that comes from the context s python inbu python Library so we're going to do that by first of all going to the top of our code right here and saying
from from Context SB we have I'm going to go ahead and import a special decorator called a sync context manager and once we've created that now we're going to determine which code is going
to run at the start of our application and which code is going to run at the end of our application so to do that
we're going to go right here and say at async context manager and then we're going to define a core routine that is going to run throughout the lifespan of
our application so we're going to Define this as our life span and this is going to be uh a function called lifespan but it's going to take in one important attribute which
is going to be an app instance so this is going to be of type first API now once you've been able to do that it's time for us to determine which code
is going to run at the start of our app and which code is going to run at the end of our app so to do that we're going to first of all write two print statement one is going to run at the
start of our application and another one is going to run when we stop our server so let us go ahead and do this we shall say print server is
starting and once that is done then we're going to also print server has has been
stopped so once we've been able to do this we have two print statements one saying one indicating that the server has been started and another one indicating that the server has been
stopped how can we separate these two to make them not run at the same time or how can we make this run in an order where the first one is running at the
start of our server and the second run is running at the stopping of our server when we stop our server so this is where the yield is going to come in so for us
to do that we're just simply going to introduce the yield word right here and this keyword is going to determine which code is going to run first and which
code is going to run at the end of our application so just have this in mind you don't have to memorize it the moment you define your lifespan event and decorate it with the assen context
manager the Cod going to run at the top of the yeld statement is the one that shall start at the server and then the one that will run after your yield statement right here is one that's going
to run when our server stops so when we have defined our lifespan event we also have to go ahead and sort of register it to our first API instance and the way we
do that is by coming to the first API instance that we created right here and then we can simply go ahead and say lifespan and then we point to that specific life
span event we've created right here so that's going to be equal to life span so to test the working of this the first thing we're going to do is to go ahead and run our server so we're going to
pull up our server with first API Dev and then our source folder now one thing we are noticing is we're getting this error right here that is telling us that our generator object is not an async
iterator so let's go ahead and fix this so when we take a look look at our lifespan event right here it seem like we have to Define it as an
async function and that is not something that I have done or something that I have forgotten so what I going to do is to introduce it I'll come right here and say a sync Def and then life span so
this is going to go ahead and run our server is starting PR statement just like you see right here so if we press contrl and C we're going to notice that
server has been stopped is going to be run so just like that we' been able to set up a lifespan event now let us look at how we can create a database
connection at the start of our server so I'm going to go back to our main.py
where I created our engine object and the first thing we're going to do is to create sort of like a function that we're going to run at the start of our application to help us to create a
database connection so I'm going to come right here and what I'm going to do is to create an async function and I going to
call this async function in it DB so this un DB function is going to be one that's going to allow us to create a connection to our database and keep that
connection for as long as our application is running so I'm going to start by using our sync or by using our engine object that we've created right
here so we me to create an a sync with statement and what this is going to do is help us to create a connection object and then we shall carry out a simple SQL
statement on our database now let us get started by doing a sync with and inside here we're going to begin by creating our engine object so we're going to call
that engine do begin method and once we call that engine begin method we are going to access the connection
object via that meod so now that we've created our connection let us go ahead and create our statement that we're going to execute on our simple database
so to do that we're going to create a variable called statement and statement is going to be equal to a simple select statement but for us to carry out a
statement we are going to need to express this in terms of text so esql model provides a text function that can
be used to turn a text or a string SQL statement into an actual SQL statement that we can then use our connection to run on our database so we're going to begin by going ahead and importing it so
I'm just going to go at the top right here and import the text function then I'm going to come right here and say text and then we shall run our simple SQL so just like you see right here
we're going to create an expression representing a textural SQL string so shall just come right here and say select and all we want to do is to
select the word hello or to run the word hello on our database so this is going to be executed as an SQL statement so we're going to close
this and once you've been able to do that now let's go ahead and run this using our connection object so to run our run our statement using our SQL
we're going to create a result object and this result object is going to be a result of using our connection to run
that statement so you need to say con do execute and in this case we shall provide the statement that we are trying to run on our database so this is going
to be our statement just like you see right here and as we need to access all the results we are simply going to go ahead and run
result do all and this is going to be able to run our select statement so so let us go ahead and run this so to begin
I'm going to go right where we have our live span event and instead of having to run the print statements I'm going to go ahead and run this INB function that
we've created right here so I'm going to go at the top right here and I'll begin by importing that so I'll say from
source.
DB do main we are going to access our init DB function and once you've been able to do that now let's go ahead and
run this so I'll call init DB or let me go ahead and run it after the survey starting statement now keep in mind that any DB is a call routine and therefore
if we need to run it we need to call it with a weight so whenever you define an async function for you to be able to call it
you have to call it with a weight so we're going to go ahead and save and rerun our server with first API Def and then
source and now we shall see what is going to happen so when you run our server notice what is going to happen since we set EO to true we are going to
notice that some SQL is going to be executed and it's going to be logged within our console so right here we see that the select sement has been run which is Select hello and the output of
that has been printed right here so we have a list but that list has a result that is our hello that we've selected on top of our database so this shows that
we have been successful in connecting to our poql database now that we've been able to do that let us go ahead and create a database model for our book
data once we've created that model we are now going to go ahead and create read update and delete book objects in a real persistent poql database so to do
that we are now going to go ahead and inside our books module or books package we're going to create a new file and we're going to call that
model.py so model.py is going to be the
model.py so model.py is going to be the special file in which you're going to have a database model for a specific entity if we have let's say the user
model we shall have that located in its package and then models. pii if you have reviews model then we have that in reviews model.py just like we're going
reviews model.py just like we're going to see now let us Begin by creating our simple model so our model is going to be very similar to what we have inside our
schema for books however we're going to add on some extra Fields just like we're going to see in fact let me go ahead and just copy what we have
here and then I'll paste it within our models.py so you're also going to notice
models.py so you're also going to notice that a pantic model is is actually going to be very similar to an SQL model in fact we're going to get rid of this and
we shall only be using our model so I'll go back to models right here so I'll begin by first of all pasting it right here and instead of base model in this
case I'm going to be using the SQL model class so for us to create a pantic model or an SQL model actually we have to go
ahead and import our SQL model class so we shall say from SQL model but we have we don't have it installed so we have to go ahead and do that so I'll open up my
terminal within our virtual environment and then we shall say from oh this is actually going to be pip
install SQL model oh seem like we installed it already so I'll go ahead and use it so I'll say
from SQL model I wonder why I forgot that I install it so shall sa from SQL model we're going to go ahead and import our SQL model class now I'm calling this
SQL but you can call it SQL or anything you want I hope that doesn't irritate you so once you've created this book model we're now going to go ahead and
sub class the SQL model but for us to make this a table class then we're going to also provide one important argument that's going to be the table argument so
we're going to go in here and then we shall say the table is going to to be equal to true so once that is done we have our Fields but we're going to also introduce
two time stamps that are going to be for the created at date as well as the updated at date so I'm going to come right here and say that this is going to be created
at and then we shall have this being a daytime object so I'll go ahead and import the daytime CL class so I'll say
from date time we are going to go ahead and import our date time object so once that is done then let's
annotate that with the type of date time and also do the same thing for the updated at time so the updated updated at dat time is going to be equal to that
all right another thing we're going to do is to change our database model so that instead of having an ID that is an integer we actually have a unique
identifier or a uu ID and this unique identifier is going to be one that's going to be unique to any object that shall ever create in our database so for
us to do that we're going to be making use of pantic field function and what this does is to allow us to Define extra
attributes that may belong to a specific field on a pantic model using that we can also go ahead and specify the database types or the SQL Alchemy database types for a specific field
let's say you wanted to customize a field so that it has post SQL specific types then that is what you're going to be using now databases such as SQ light may not
have the support for uids but when using post SQL or MySQL you can be able to use the uuid type so
let us go ahead and set that up we're going to begin with the ID field or what we have as our ID field so I'm going to begin by changing it from ID to UU ID
and then instead of integer I am going to set this up to be using The UU ID type so The UU ID type is present within the U ID module that's present within
python so I'll go ahead and import that I'll say from uu ID we are going to be making use of our uu ID class and once
we have that then we are going to go ahead and say this is going to be our u u ID another thing we can do is to just simply import uu ID or what I can
actually do is to just say import uu ID so that I can easily access everything of the U ID module now once this is done we need to
go ahead and specify the exact way we want to store our uu IDs so I begin by importing the field function I'll go at the top right here and say from SQL model we're going to import field and
once we've been able to import that then this is going to be a pantic field and this is going to also have the SQL Alchemy column why because we are going
to be accessing the specific U ID type for post SQL and that's what we want to store our uu IDs with so first to use
SQL Alchemy column types or specific attributes and stuff all we're going to do is to access the sa column attribute and then we are going to
Define this field as though we were defining an SQL Alchemy field so to begin we're going to make sure we get access to the column class and with that
column class we're going to Define whatever I want to Define on this specific module so we're going to come right here and say that we need to get the column class class so once we've
imported the column class we're going to Define this as a column and then this column is going to take in the type of that specific field so we need to first
of all go ahead and import it and this is going to be the poql ID tape so I'll come and import the dialect for post SQL that's going to allow us to access all
the field types as they are on our po SQL database so I'll say import SQL Alchemy so sorry for this so
this is going to be import SQL Alchemy do dialect do poql so you can also access other dialects right here you
have those for poql MySQL Oracle and SQL but in this case we are using poql so I'm going to go ahead and say poql and want to go ahead in and import
it as PG so we're going to be accessing everything via PG so this is going to be import as PG I
think I've made a mistake right here so it's going to be as PG now once we've been able to do this let's go ahead and
set our type up so we're going to provide our type in here as our PG do uu
ID and once that is done let's define other constraints so we can say this is not going to be nullable so we can say nullable equals to false and then we can also do other
things such as setting the primary key attribute so we can say our primary key is going to be equal to true and we can also say that this is
going to have a default so we can set the default by using this column class so we can say that this going to have a default but our default is going to be a newly generated U ID for us to generate
a new U ID all we have to do is to call a uu ID function or call function that create specific types of U IDs so I'll
say default is going to be U ID Dot and in this case we shall call the function U ID for so we need to create a uu ID
for type of uu ID and this is going to be enough for us to Define our primary key column now another thing we're going to do is to define the table name of
this class and the way you do that is by using SQL alchem is table name attributes so we're going to come right here and say that our table name is going to be equal to books and
that is going to be just enough for us to set the table name of that specific table so the rest of this can also be set up but I'm going to Simply leave
them out except for the created art and the updated art time STS I'm going to Define them as type stamps from the
poql dialect so I'll just go ahead and Define them as what we've done for this I'm going to do that by saying this is going to be a to field and the field is
going to be so right in here we're going to come and say the our field is going to be a column and this column is going to be of
type pg.
timestamp and then uh right in there we we are going to also go ahead and set up the default so I'm going to say that the default is
going to be equal to so in this case we shall just say date time dot now and I'll do the same thing for the
updated that so I'll just come right here or let me just actually leave it to this but let me just leave it to default equals to updated which is
now so we shall also look at how we can set this when updating each of the book objects so once you've been able to Define this object now we can also
Define a method on this class that's going to be responsible for giving us a string representation of the book object we've stored in our database now for us
to do that we are going to go ahead and say Def and this is going to be our D RI and this shall take in self now what
this is going to do is to return and of type book but it's going to return it in a very readable format so we shall say
book and in this case we shall return self. tile which is the title of that
self. tile which is the title of that specific book that we shall be accessing at a given point all right we've been
able to create our database model now we need a way for us to create this in our database and we're going to to achieve this using our lifespan event that we created in
the previous sections and this is going to be very easy because all we're going to do is to be using the metad DAT that's going to be present on our SQL
model so the metadata is simply the data about the database and once we Define any class with the SQL model we get
access to the metad DAT present on our SQL model class and whatever class is defined there is going to be created by calling a specific method called the
create all method so once we've been able to do that our database tables will be created in our database and we shall now be able to go ahead and run
our run our CR just like we did in the previous video now to do that we're going to go within our main.py and we going to modify our init DB function so
that it actually goes ahead and creates our database now for us to do this we're going to come right in here and remove what we have and instead of running a
simple SQL statement on our database we are now going to go ahead and create database tables in our database so to begin we're going to have to first of
all import the model that we've created inside our models folder or our mod module right here so I'm going to go ahead and access that I'll come at the
top of our code and say from it's going to be source.
books. mod we are going to go ahead and import our book model or we can actually also import it from here and once we've been able to import
it from there then we're going to go ahead and call the SQL model class and to do that we're going to have to go ahead and import it so I'll say from SQL
model which is actually already imported at the top we shall import our SQL model class and once we've been able to import
our SQL model class now let's go ahead and call a specific method that's going to be the one to help us to run synchronous code with our connection
object now that special method is going to be the cor trans sync method and that is going to be running any synchronized function within this context that is a
sync so shall come and say that this going to be a weight and in this case we shall run
con which is our connection object do run sync which is run synchronus or run any synchronous code and in this case what want to do is to access the
metadata object on top of this SQL model so shall say s ql model Dot and we shall
get access to the metadata object then on that we can call create all and that is one that's going to run our create
all statement so this is going to scan for any models that have created any models that have been created using this SQL model object and to access the
metadata and using that metadata it will go ahead and create these tables in our database so when we save and go back to our server we're now
going to notice that our server is going to restart and by restarting it is now going to call this method right here and all the SQL that has taken place is
going to be working fine so we're going to have accurate table books and this is going to create the different fields that we have on our database or the ones
that we've defined within our model that we have right here so just like that we've been able to successfully create our database table now let us go ahead and confirm if our
table has been created now if you're using neon it has a very nice user interface that can allow you to see your database table but I'm going to be digging into the shell and then
inspecting the table that has been created within our database so to do that I'm going to go back to mymin right here and then I'll connect to that
specific DB which is our bookly DB and once I connected to it now I'm going to go ahead and list the tables that are present on that specific
database of which I have only one which is our books database and once I have that then I'm going to go ahead and describe it so I'll say d and then books
and that is going to show us the structure of our book database so we've created the U ID which is a u ID type just like you see right here author is
string publisher is character varying publish date character varying of which this can also be set to a date now I think I'm going to fix this and also we can have our page count our language
created art updated art and also our indices so we have the primary key being set to The UU ID just like you see right
here so in this video we've been able to create our database using post SQL and SQL model I hope you've learned from this video and if you've done so please
leave a like on this video do not forget to share this video with whom it may be helpful and I hope you've learned from this video if you have any comments about what you've learned from this
video please uh go down in the comment section and leave your feedback on this video in the coming video we're going to be building on top of what we have for now and then carrying out the CR just
like we did for the previous videos thank you guys for watching and I'll see you in the next video bye
Loading video analysis...