Latest / CyberSecurity Summary / PostgreSQL Server Programming
Transcript
- 0:00Speaker 1: Okay, let's unpack this. If you think of Postgres School
- 0:02Speaker 1: server is just you know, place to store data like
- 0:05Speaker 1: a big passive bucket, you're missing out on a tremendous
- 0:07Speaker 1: amount of power. Today we're diving into Postgres School server programming.
- 0:12Speaker 1: We're drawing from some really insightful excerpts from the technical
- 0:15Speaker 1: book Postgreschool Server Programming. Our mission really is to show
- 0:19Speaker 1: you how Postgres School can actually be seen as an
- 0:21Speaker 1: application development framework.
- 0:23Speaker 2: Now.
- 0:24Speaker 1: Pushing logic directly to the database layer offers well shortcuts
- 0:28Speaker 1: to building faster, more secure, and highly maintainable applications. Yeah.
- 0:33Speaker 2: And what's fascinating here is we're not just talking about
- 0:36Speaker 2: database administration and the traditional sense, not at all. We're
- 0:39Speaker 2: exploring how the database itself can become like a proactive,
- 0:44Speaker 2: intelligent part of your application's core logic.
- 0:46Speaker 1: Right.
- 0:46Speaker 2: It stops being just passive storage and starts being an
- 0:48Speaker 2: active participant, your single source of truth for business rules.
- 0:52Speaker 2: You know, hashtag tag the transformative power of server programming.
- 0:55Speaker 1: So let's challenge that whole data bucket philosophy. Yeah, imagine
- 0:59Speaker 1: a common situation like a bank transfer. Say Bob wants
- 1:02Speaker 1: to send I don't know fourteen dollars to Mary h
- 1:05Speaker 1: The typical way you might write separate sequl commands from
- 1:07Speaker 1: your application, right, want to take money from Bob a debit,
- 1:10Speaker 1: another to give to Mary a credit? But I mean
- 1:13Speaker 1: think about the problems there at first security, Do your
- 1:16Speaker 1: app really need to know Bob's balance or just can't
- 1:19Speaker 1: he send the money?
- 1:20Speaker 2: That's a big one.
- 1:21Speaker 1: Then speed, you've got multiple round trips to the database
- 1:24Speaker 1: slows things down. And the big one integrity. What if
- 1:28Speaker 1: the system crashes halfway through, Bob's money is gone, Mary
- 1:31Speaker 1: never gets it.
- 1:32Speaker 2: Nightmare scenario exactly, And that's precisely why server programming is
- 1:35Speaker 2: such a well a game changer. By executing that transfer
- 1:39Speaker 2: logic directly on the database server, you're centralizing it. It's
- 1:42Speaker 2: not just tidy code. It's a fundamental shift. You're putting
- 1:46Speaker 2: the rules in the most robust place, the database itself.
- 1:50Speaker 2: It becomes this active.
- 1:52Speaker 1: Partner active partner.
- 1:53Speaker 2: I like that, and it cuts out all those network
- 1:55Speaker 2: round trips, so it's way faster. You write a function.
- 1:59Speaker 2: Maybe in plpg's it does all the checks, does Bob
- 2:02Speaker 2: exist enough funds, is Merry valid? And it just returns okay,
- 2:06Speaker 2: or you know, not enough funds. The client app doesn't
- 2:09Speaker 2: need the details, just the success or failure. No sensitive
- 2:12Speaker 2: data leakage.
- 2:13Speaker 1: That is incredibly powerful for security, for consistency, yeah yeah,
- 2:19Speaker 1: But what if you want the database to react automatically
- 2:21Speaker 1: like inventory management, stock levels, change offers, need updating instantly,
- 2:26Speaker 1: no app involved triggers.
- 2:28Speaker 2: That's exactly what triggers are for magic pretty much. They
- 2:31Speaker 2: let operations in the database automatically cause other things to happen.
- 2:35Speaker 2: So say you've got your fruit sinstock and your fruit
- 2:37Speaker 2: offer tables, A trigger can make sure that when you
- 2:40Speaker 2: update an offer amount for apples, uh huh, the reserved
- 2:43Speaker 2: count in fruits in stock just adjusts automatically. It stops
- 2:46Speaker 2: you over reserving, stops you selling stock that's already spoken for,
- 2:49Speaker 2: even across different tables. It enforces that link.
- 2:52Speaker 1: Okay, that's clever.
- 2:53Speaker 2: And building on that automatic reaction idea, triggers are fantastic
- 2:58Speaker 2: for auditing, indispensable. You can set one up to log
- 3:02Speaker 2: every single action on important tables like imagine a salary's table.
- 3:06Speaker 2: An audit trigger can grab the username, the timestamp, the
- 3:09Speaker 2: operation type, insert, update, delete, and even capture the old
- 3:13Speaker 2: salary and the new salary. Maybe store the whole old
- 3:15Speaker 2: and new row as JSON for a complete record. It's
- 3:18Speaker 2: a rock solid audit trail. It's automatic, totally automatic. Plus
- 3:22Speaker 2: triggers can enforce data consistency, simple things like automatically converting
- 3:27Speaker 2: an employee name to uppercase whenever it's inserted or updated.
- 3:31Speaker 2: Ensures uniformity. You know, no need to rely on every
- 3:34Speaker 2: client app remembering the rule.
- 3:36Speaker 1: So functions, centralized logic, triggers automate reactions. But what about
- 3:41Speaker 1: teaching postcress new tricks entirely? What does extensibility really mean here?
- 3:46Speaker 1: Is it just more functions?
- 3:47Speaker 2: Oh, It's much more profound than just functions. Extensibility means
- 3:50Speaker 2: you can actually extend postgres school itself. It's language, it's capabilities.
- 3:54Speaker 2: You can define your own custom data types like uh
- 3:58Speaker 2: fruity maybe that understands bushels. And you can teach it
- 4:01Speaker 2: custom operators like how to compare apples and oranges directly
- 4:05Speaker 2: in a query? H seriously, well metaphorically maybe, But you
- 4:10Speaker 2: can define operators for your custom types. And yes, user
- 4:14Speaker 2: define functions. UDFs are a huge part, and these functions
- 4:17Speaker 2: can get sophisticated. They can handle complex arguments like XML
- 4:21Speaker 2: or JSON or return results in those formats too great
- 4:25Speaker 2: for modern architectures like SOA or micro services.
- 4:28Speaker 1: Right makes sense, and you mentioned performance earlier. Extensibility ties
- 4:32Speaker 1: into that too, especially server side caching.
- 4:34Speaker 2: Absolutely, server side casing is a classic pattern enabled by functions.
- 4:38Speaker 2: The logic is simple. Really, inside your function, first check
- 4:42Speaker 2: if the value you need is already cashed, maybe in
- 4:44Speaker 2: a table. Is it there, is it recent enough? If yes, great,
- 4:47Speaker 2: return it. If not, compute it, store it in the cash,
- 4:50Speaker 2: then retun it.
- 4:51Speaker 1: So next time it's fast.
- 4:52Speaker 2: Exactly. Think about calculating total company sales that might involve
- 4:56Speaker 2: querying thousands of rows cash the result. There's this great
- 5:00Speaker 2: story about a Java e email system. It was sending
- 5:04Speaker 2: maybe a few hundred emails a second, okay, but not amazing.
- 5:08Speaker 2: Then someone rewrote the email generation part as ap peel
- 5:12Speaker 2: Peril function inside.
- 5:13Speaker 1: Postgres school, inside the database.
- 5:15Speaker 2: Inside the database, suddenly it wasn't sending hundreds, It was
- 5:18Speaker 2: spewing out tens of thousands of emails per second.
- 5:21Speaker 1: Wow, that's that's incredible.
- 5:23Speaker 2: It was all because the computation happened near data minimal
- 5:27Speaker 2: network latency. It went from like a two point two
- 5:30Speaker 2: millisecond query from the client to zero point one to
- 5:33Speaker 2: two milliseconds inside the database. Huge difference.
- 5:36Speaker 1: That is a massive jump, and you can see how
- 5:38Speaker 1: that ties into maintenance and security too. If all your
- 5:41Speaker 1: core data logic is in database functions or views, upgrading
- 5:45Speaker 1: is just running a script, a detail.
- 5:48Speaker 2: Script, YEP, data definition language. You update the function in
- 5:51Speaker 2: the database.
- 5:52Speaker 1: No downtime, no complex roll out across all your different.
- 5:55Speaker 2: Client apps, exactly. All clients just start using the new
- 5:57Speaker 2: logic immediately. It simplifies maintenance enormously. It's security big win
- 6:01Speaker 2: there too. If you grant database users permission to execute
- 6:05Speaker 2: only specific functions, not direct access to tables, then even
- 6:09Speaker 2: if an attacker compromises your web server, say, they can't
- 6:12Speaker 2: just run select from users and dump all your data.
- 6:16Speaker 1: They can only run the functions you've a looked.
- 6:17Speaker 2: What you've designed to be safe right to only return
- 6:20Speaker 2: specific non sensitive info or perform validated actions. It drastically
- 6:25Speaker 2: reduces the attack surface hashtag tag tech trag y. Postgress
- 6:28Speaker 2: School the environment advantage.
- 6:31Speaker 1: So, okay, putting lodging in the database is powerful, we
- 6:34Speaker 1: get that, but why postgres school specifically, what makes it
- 6:38Speaker 1: the go to platform for this kind of server programming.
- 6:42Speaker 2: Well, first off, the cost of acquisition.
- 6:44Speaker 1: It's zero. Can't be free, right.
- 6:46Speaker 2: Compare that to commercial databases SEQL server Oracle. You're talking
- 6:51Speaker 2: potentially thousands, even tens of thousands in licensing fees. Postgress
- 6:55Speaker 2: will costs nothing to download, nothing to use, and this
- 6:58Speaker 2: directly leads to a low cost of failure. When you're
- 7:00Speaker 2: starting a project things are uncertain, you might experiment change direction.
- 7:04Speaker 2: Being able to try things out, even scrap an idea
- 7:07Speaker 2: without being locked into expensive long term licenses, that's a
- 7:10Speaker 2: huge advantage. It frees you up to.
- 7:12Speaker 1: Innovate definitely, and that ties into licensing more broadly, doesn't it.
- 7:16Speaker 1: I remember the unease when Oracle bought my sequel that
- 7:20Speaker 1: vast and thunderous sucking sound.
- 7:22Speaker 2: Does someone put it huh, yes, exactly. There is a
- 7:25Speaker 2: lot of uncertainty about the future of my squels licensing.
- 7:28Speaker 2: Postgres School's license, though, is incredibly liberal bs D style. Basically,
- 7:33Speaker 2: you can have the source code, do anything with it
- 7:36Speaker 2: that you want, redistribute it however you jolly well please,
- 7:40Speaker 2: and those rights extend indefinitely.
- 7:42Speaker 1: Wow.
- 7:43Speaker 2: For companies, that removes massive legal risk. You know, the
- 7:46Speaker 2: terms won't suddenly change. You know, you can build products
- 7:49Speaker 2: on it without unexpected fees popping up.
- 7:51Speaker 1: That's huge peace of mind.
- 7:52Speaker 2: Then there's predictability. Postgreds School is known for sticking really
- 7:56Speaker 2: closely to SQL standards. Now, sometimes that might feel a
- 7:59Speaker 2: bit stricter, maybe less forgiving than other databases if you
- 8:01Speaker 2: write slightly nonstandard sequel, but the upside is fewer unintended behaviors,
- 8:07Speaker 2: fewer surprises. You know it's going to work the way
- 8:10Speaker 2: the documentation says it works. That means less chance of
- 8:13Speaker 2: your application breaking in subtle ways down the road because
- 8:16Speaker 2: of some weird database quirk. It provides a really stable foundation.
- 8:19Speaker 2: You can trust it.
- 8:21Speaker 1: Okay, stability, predictability, Yeah, what else? You mentioned something about
- 8:26Speaker 1: the community earlier.
- 8:27Speaker 2: Ah, yeah, the community aspect is actually really interesting and
- 8:30Speaker 2: often overlooked. With commercial databases, trying to talk to the
- 8:33Speaker 2: actual core developers, good luck, you're usually dealing with layers of.
- 8:38Speaker 1: Support stat right ticketing systems.
- 8:40Speaker 2: Exactly with postgres School, many of the core developers hang
- 8:43Speaker 2: out on IRC channels, they go to conferences, you can
- 8:46Speaker 2: actually talk to them.
- 8:47Speaker 1: And they like beer apparently.
- 8:48Speaker 2: Well the book mentions that, But the point is there's
- 8:51Speaker 2: this direct connection. It fosters a real sense of shared
- 8:55Speaker 2: ownership and concern for the project's health. Expert help is
- 8:58Speaker 2: often just a question of a way. It's a very
- 9:00Speaker 2: vibrant ecosystem.
- 9:02Speaker 1: That's a really different feel.
- 9:03Speaker 2: Definitely, and technically a huge advantage is its support for
- 9:07Speaker 2: multiple procedural languages. It's not just plpgcquall the built in one.
- 9:11Speaker 2: You can write server side functions in Python, Perl, TCL,
- 9:15Speaker 2: even C.
- 9:16Speaker 1: And you can add or remove these languages on.
- 9:18Speaker 2: A running server, no downtime needed to install, Say peel
- 9:21Speaker 2: Python support and think back to our earlier example. The
- 9:25Speaker 2: bad way of doing things maybe with PHP connecting, pulling data,
- 9:29Speaker 2: figuring things out client side, then sending an update back.
- 9:32Speaker 1: Right, the multiple roundtrips, the potential integrity issues exactly.
- 9:35Speaker 2: That leads to terrible scalability. The right way is pushing
- 9:39Speaker 2: that logic into a database function using one of these
- 9:42Speaker 2: powerful languages. A single efficient.
- 9:45Speaker 1: Call makes sense. What about transactions? How does post grace
- 9:48Speaker 1: handle those?
- 9:49Speaker 2: It's very sensible, very safe. By default. The standard isolation
- 9:52Speaker 2: level is read committed me, meaning your transaction will only
- 9:56Speaker 2: ever see data that has been fully committed, fully saved
- 9:59Speaker 2: by other transactions. You don't get dirty reads seeing incomplete
- 10:03Speaker 2: changes that might get rolled back later. That avoids a
- 10:05Speaker 2: whole class of bugs.
- 10:06Speaker 1: That sounds safer it is.
- 10:08Speaker 2: And by default, each individual seql statement you send acts
- 10:12Speaker 2: as its own little transaction. It commits immediately, though client
- 10:15Speaker 2: tools like fusequal often wrap things in a transaction block automatically.
- 10:19Speaker 2: If you're typing multiple commands okay, and one more thing
- 10:22Speaker 2: on control postgrescool gives you more control over how your
- 10:26Speaker 2: functions execute, specifically around security, their security and voker. That's
- 10:31Speaker 2: the default. The function runs with the permissions of the
- 10:34Speaker 2: user calling it, but there's also security definer. This is
- 10:38Speaker 2: really useful. The function runs with the permissions of the
- 10:40Speaker 2: user who created it.
- 10:41Speaker 1: Ah, so you could let a less privileged user run
- 10:45Speaker 1: a function that needs higher privileges for a very specific controlled.
- 10:49Speaker 2: Task, precisely temporary safe privilege escalation. They can't access the
- 10:55Speaker 2: underlying table directly, but they can call the function which
- 10:57Speaker 2: performs a specific safe action on their behalf. And you
- 11:00Speaker 2: can also define a cost for a function. This is
- 11:03Speaker 2: like giving a hint to the query planner, the.
- 11:05Speaker 1: Part of the database that figures out how to run queries.
- 11:07Speaker 2: Yeah, you can tell it. Hey, this function is really
- 11:09Speaker 2: expensive to run, so the planner will try to avoid
- 11:12Speaker 2: calling it too often if it can find a cheaper
- 11:14Speaker 2: way to get the result. Helps optimize overall performance. Hashtag
- 11:18Speaker 2: hashtag deep dive into language capabilities and advanced techniques.
- 11:22Speaker 1: Okay, let's dive into some of the actual coding. Then
- 11:24Speaker 1: the warkhorse so PLPG SQUL you called it the workhoorse.
- 11:27Speaker 1: It's built in, no extra setup needed. What makes it
- 11:30Speaker 1: so fundamental for server side logic and postgress.
- 11:34Speaker 2: It's just incredibly well suited for combining SQL with procedural logic,
- 11:39Speaker 2: you know, if statements, loops, variables. It's great for encapsulating
- 11:43Speaker 2: those multi step operations we talked about, like the bank transfer.
- 11:46Speaker 2: You can access function arguments easily, either by their position
- 11:49Speaker 2: or by a name. You've got your standard of penols,
- 11:51Speaker 2: your case. Statements for conditional logic loops are there too.
- 11:54Speaker 2: But a really important warning. Looping through query results inside
- 11:59Speaker 2: plpg'sl Generally that's considered doing it wrong. It's usually very inefficient,
- 12:05Speaker 2: high processor cost, high memory use. SQL is designed for
- 12:09Speaker 2: set based operations. You should almost always try to find
- 12:12Speaker 2: a way to express your logic using SQL sets rather
- 12:16Speaker 2: than row biro looping in plpg sql let the database
- 12:20Speaker 2: engine optimize the set operation.
- 12:22Speaker 1: Good tip. Okay, what about getting results out of functions?
- 12:25Speaker 2: Right? You use perform if you just want to execute
- 12:29Speaker 2: a query for its side effects like an insert or update,
- 12:31Speaker 2: and you don't care about the result. If you do
- 12:33Speaker 2: need the result, you use select into to put it
- 12:35Speaker 2: into a variable.
- 12:36Speaker 1: Makes sense. And you can return more than just single
- 12:39Speaker 1: values right like lists or tables?
- 12:41Speaker 2: Oh yeah, absolutely, you can return a set of integer
- 12:44Speaker 2: like generating the Fibonacci sequence. You can return set of
- 12:48Speaker 2: table name, which effectively returns rows matching that table structure.
- 12:52Speaker 2: You can define functions with out parameters which become part
- 12:55Speaker 2: of the result row, or use the very clear returns
- 12:58Speaker 2: table syntax to define the output columns right there.
- 13:01Speaker 1: What if the structure isn't known beforehand?
- 13:03Speaker 2: Good question. You can use return set off record, but
- 13:06Speaker 2: then you have to provide a column definition list when
- 13:09Speaker 2: you call the function. More flexibly, you can use polymorphic
- 13:12Speaker 2: types like set off an element or set off any
- 13:14Speaker 2: compatible for functions that can work with or return different
- 13:18Speaker 2: but related types. And there's variatic arguments, which lets a
- 13:22Speaker 2: function accept an arbitrary number of arguments of a certain
- 13:25Speaker 2: type past as an array super flexible.
- 13:27Speaker 1: You also mentioned cursors briefly before for large results.
- 13:31Speaker 2: Right reef Cursors specifically, cursors are internal structures that let
- 13:35Speaker 2: you fetch query results incrementally lazily, instead of the database
- 13:39Speaker 2: computing the entire results set and sending it all at once,
- 13:42Speaker 2: which could take ages and lots of memory. For huge queries,
- 13:45Speaker 2: you get a pointer kinda yeah, a reference. Then your
- 13:48Speaker 2: application can fetch rows from that cursor as needed. It's
- 13:52Speaker 2: great if you only need the first few rows quickly,
- 13:54Speaker 2: or if you want to return multiple independent result sets
- 13:57Speaker 2: from a single function. Call PLPGCQ trigger functions Automated guardians no.
- 14:03Speaker 1: Get back to triggers. These automatic guardians you said, they
- 14:05Speaker 1: get old and NW records. How does that actually work
- 14:08Speaker 1: in the code.
- 14:09Speaker 2: So when you write a trigger function one that returns
- 14:12Speaker 2: trigger postgresscool automatically makes special variables available inside it. Old
- 14:17Speaker 2: is a record variable holding the row values before the
- 14:20Speaker 2: operation for update and delete. New holds the values after
- 14:23Speaker 2: the operation for insert and update. And you also get
- 14:26Speaker 2: tg variables like TGP tells you if it was an insert,
- 14:29Speaker 2: update or delete tg table name gives you the table
- 14:32Speaker 2: name and so on. Lots of context, so.
- 14:34Speaker 1: That audit trigger example, it uses those exactly.
- 14:37Speaker 2: It would check TGOP. If it's an insert, it logs
- 14:40Speaker 2: the new record maybe converted to Jason. If delete, it
- 14:43Speaker 2: logs old. If update, it logs both old and new,
- 14:46Speaker 2: along with the username from current user timestamp now table
- 14:51Speaker 2: name and operation type creates that perfect audit law.
- 14:54Speaker 1: Very cool, and you mentioned preventing actions.
- 14:56Speaker 2: Yeah, you could have a simple trigger function that just
- 14:59Speaker 2: raises an exception if t GOP is delete or truncate
- 15:02Speaker 2: on certain critical tables, just stops the operation cold or
- 15:05Speaker 2: more subtly. In a before trigger one that runs before
- 15:08Speaker 2: the change is actually made, you can modify the new w.
- 15:11Speaker 1: Record uh like the upper case name example.
- 15:14Speaker 2: Precisely we're setting timestamps. A common pattern is a function
- 15:17Speaker 2: that sets create at and created by only on insert,
- 15:20Speaker 2: and updated at and updated by on update, ensuring those
- 15:23Speaker 2: created fields are immutable after the initial insert. But again,
- 15:27Speaker 2: the reminder triggers are powerful, but use them judiciously. For
- 15:31Speaker 2: complex application logic, they can make debugging harder because the
- 15:35Speaker 2: logic isn't always obvious in the main application code. Keep
- 15:38Speaker 2: them focused.
- 15:39Speaker 1: If you can seeing inside.
- 15:41Speaker 2: That debugging point is key. If you've got complex logic
- 15:44Speaker 2: hidden away and functions and triggers, how do you troubleshoot
- 15:47Speaker 2: when things go wrong. It's not like setting a break
- 15:48Speaker 2: point in your Java or Python code.
- 15:50Speaker 1: Is it. It's definitely different. The simplest approach is what you
- 15:53Speaker 1: might call manual debugging. Using raise notice, you just sprinkle
- 15:56Speaker 1: raise notice reached point a with value my variable throughout
- 16:02Speaker 1: your code. The messages show up in your client like
- 16:05Speaker 1: psdes col like print statements.
- 16:07Speaker 2: Basic.
- 16:08Speaker 1: It's exactly simple, no installation needed. Great for checking values
- 16:13Speaker 1: in regression test scripts. The downside is it can clutter
- 16:16Speaker 1: your output if you leave them in. For actual error handling,
- 16:19Speaker 1: you use reez exception. You can provide a custom error
- 16:23Speaker 1: message and even a specific SQL state code which client
- 16:26Speaker 1: applications can catch and react to programmatically. Okay, And if
- 16:30Speaker 1: you want messages to go to the server's log file
- 16:32Speaker 1: instead of the client maybe for background tasks or just
- 16:35Speaker 1: less noise, you use.
- 16:37Speaker 2: Raise luck right, So print debugging essentially, what about stepping
- 16:40Speaker 2: through code?
- 16:41Speaker 1: For that? You need the visual PLPG SQL debugger usually
- 16:45Speaker 1: integrates with GUI tools like PG admin once it's set up,
- 16:49Speaker 1: and the setup can be a bit of a pain.
- 16:50Speaker 1: Fair warning is pretty powerful. You can set break points
- 16:53Speaker 1: in your plpg sql.
- 16:54Speaker 2: Code like in a normal id YEP, step.
- 16:57Speaker 1: Through line by line, step into, step over, inspective values
- 17:00Speaker 1: of variables, even change variable values on the fly to
- 17:02Speaker 1: test different scenarios. You can also set global breakpoints like
- 17:06Speaker 1: stop whenever any code calls. This specific function really handy
- 17:10Speaker 1: for tracking down unexpected.
- 17:11Speaker 2: Calls and the advantages.
- 17:13Speaker 1: The big advantage over raised notice is it doesn't use
- 17:15Speaker 1: server resources when you're not actively debugging, and you don't
- 17:18Speaker 1: need to modify your function code with print statements. The
- 17:21Speaker 1: disadvantage that installation process can be fiddly. Using unrestricted languages
- 17:26Speaker 1: expanding horizons PL Python.
- 17:28Speaker 2: Okay, let's shift gears beyond PLTG squel. You mentioned unrestricted
- 17:32Speaker 2: or untrusted languages like pl python. That untrusted label, why
- 17:37Speaker 2: is it there? What's the deal? Right?
- 17:38Speaker 1: The untrusted language is pl python, PEEL, perileu, PLTCLU, peel, JAVAU.
- 17:43Speaker 1: They're called that because they break out of the database sandbox.
- 17:46Speaker 1: They can by default access the server's file system, make
- 17:50Speaker 1: network connections, send signals to other processes, basically do anything
- 17:55Speaker 1: the underlying language, Python, Perol, etc. Could do on the
- 17:58Speaker 1: host operating system.
- 17:59Speaker 2: Ahotential security risk.
- 18:01Speaker 1: Huge potential security risk. That's why you absolutely should not
- 18:03Speaker 1: grant permission to create functions in these languages to arbitrary
- 18:06Speaker 1: database users. You don't fully trust. They could potentially read
- 18:09Speaker 1: sensitive files or disrupt the server.
- 18:12Speaker 2: Got it, so why use them?
- 18:13Speaker 1: Power and convenience, Python, for example, has vast libraries for
- 18:16Speaker 1: everything imaginable. It's often much easier and requires less boilerplate
- 18:21Speaker 1: code to do complex text processing, interact with web services,
- 18:25Speaker 1: or use external libraries and peel Python that it would
- 18:27Speaker 1: be in plpg sql or especially C plus. Many developers
- 18:32Speaker 1: are already comfortable with Python and peel Python handles the
- 18:35Speaker 1: data type conversions between postcrescool types and Python types pretty
- 18:39Speaker 1: transparently for you.
- 18:40Speaker 2: Okay, so if I'm writing a pel Python function, how
- 18:42Speaker 2: do I run SQL queries from within that Python code.
- 18:45Speaker 1: Peel python provides a dedicated module usually accessed as plea high.
- 18:49Speaker 1: It has functions like peelpi dot execute to run arbitrary
- 18:53Speaker 1: SQL queries. It also has peelpi dot prepare, which lets
- 18:56Speaker 1: you create a prepared statement plan. This is really important
- 18:59Speaker 1: for performing. So if you're running the same kind of
- 19:01Speaker 1: query multiple times, maybe just with different parameters.
- 19:03Speaker 2: Prepare ones execute many times exactly.
- 19:06Speaker 1: Preparing can be costly, so caching that plan makes subsequent
- 19:10Speaker 1: executions much faster. And when you're writing a trigger function
- 19:13Speaker 1: in peel Python, instead of old and new to W variables,
- 19:16Speaker 1: you get a Python dictionary usually called TD, which contains
- 19:19Speaker 1: all the trigger context td ol, td new, tdvn td, win,
- 19:22Speaker 1: et cetera. Right, what about dynamic sqel building queris on
- 19:25Speaker 1: the fly? Huge risk of seql injection There absolutely critical point.
- 19:29Speaker 1: You should never just concatenate strings together with user input
- 19:33Speaker 1: to build SQL queries in any language, including PL Python.
- 19:36Speaker 1: Plupy provides functions specifically for safe quoting Peelpi dot quote
- 19:40Speaker 1: item for table or column names, peelpi dot quote literal
- 19:43Speaker 1: for string values, and peelpi dot quote nullable which handles
- 19:46Speaker 1: nls correctly. Always use these when incorporating external data into
- 19:51Speaker 1: dynamic queries. It's your primary defense. Good advice. How does
- 19:54Speaker 1: error handling work within PL Python? Does it interact with
- 19:57Speaker 1: database transactions? You use standard Python t dot accept blocks
- 20:01Speaker 1: to catch errors that might occur within your Python code
- 20:04Speaker 1: or from SQL queries executed via PLI. For transactional control
- 20:08Speaker 1: within your function, pl Python provides PLPI dot subtransaction. This
- 20:13Speaker 1: lets you create save points. You can wrap a block
- 20:16Speaker 1: of code and a subtransaction context manager, and if an
- 20:18Speaker 1: exception occurs inside that block, only the database changes made
- 20:22Speaker 1: within that block are rolled back ah.
- 20:24Speaker 2: So you can contain failures exactly.
- 20:26Speaker 1: It's important to note, though, that this only rolls back
- 20:29Speaker 1: database changes. Any changes to your Python variables within that
- 20:32Speaker 1: block will persist unless you explicitly handle them in your
- 20:35Speaker 1: accept clause. Python's atomicity is separate from the databases.
- 20:39Speaker 2: Right and debugging pl pythons still no visible debugger I guess.
- 20:43Speaker 1: Not built in no, so you fall back to similar
- 20:45Speaker 1: techniques as with plpg sqel, but using pythons tools dot
- 20:49Speaker 1: PLIPI dot notice, PLPI dot warning, pelpi dot error to
- 20:52Speaker 1: send messages standard Python A certain statements are useful too.
- 20:55Speaker 1: You can also redirect pythonsys dot sit out and syst
- 20:58Speaker 1: dot sitch a dor within your function and to send
- 21:00Speaker 1: output to the postgrec will server log file, which could
- 21:03Speaker 1: be helpful. But the real power here is doing things
- 21:05Speaker 1: you just wouldn't normally think of doing inside a database,
- 21:08Speaker 1: generating image thumbnails using Python's PIL library, sending emails using SENTIMENTPLIP,
- 21:13Speaker 1: Interacting with external APIs all possible directly from database functions.
- 21:18Speaker 1: With pl python. It really encourages thinking outside the SQL box,
- 21:22Speaker 1: writing advanced functions and c raw power.
- 21:24Speaker 2: Okay, peel python opens up a lot, But then there's
- 21:26Speaker 2: C writing functions directly and C that sounds like the
- 21:28Speaker 2: ultimate level of integration and probably complexity. When you absolutely
- 21:33Speaker 2: need C, you go to C.
- 21:34Speaker 1: When you need the absolute bare metal performance, or what
- 21:38Speaker 1: do you need to interact with Postgrescol's internal APIs at
- 21:41Speaker 1: a level that interprets languages just can't reach. Think extremely
- 21:45Speaker 1: computationally intensive algorithms or functions that need to process millions
- 21:49Speaker 1: of rows per second with minimal overhead, or maybe tightly
- 21:52Speaker 1: integrate with operating.
- 21:53Speaker 2: System features, and how does it work? Is it complicated?
- 21:56Speaker 1: There's definitely more ceremony involved than with plpg sql or
- 22:00Speaker 1: peel Python. You need to include specific postgress will header
- 22:03Speaker 1: files postgress dot HfN gr dot H. You need a
- 22:07Speaker 1: special macro pg modumi magic to identify the compiled object
- 22:11Speaker 1: as compatible. Each C function needs to be declared with
- 22:14Speaker 1: PGF function in ov one and to use specific C
- 22:17Speaker 1: macros like pg targin thirty two to get arguments and
- 22:20Speaker 1: pg turn in thirty two to return values. Some more boilerplate,
- 22:24Speaker 1: A bit more, yes, but the built process is actually
- 22:26Speaker 1: quite streamlined now thanks to pdxs posts wll's extension building infrastructure.
- 22:30Speaker 1: You typically just write a simple make file, run make
- 22:32Speaker 1: and then pseudo make install and postcress will knows how
- 22:35Speaker 1: to compile and link your C code correctly. Then you
- 22:37Speaker 1: just create function and SQL to link it.
- 22:39Speaker 2: Okay, not too bad. What about advanced features in C functions?
- 22:42Speaker 2: Handling NL's, For.
- 22:43Speaker 1: Instance, C requires explicit handling of nls. Unlike plpg sql,
- 22:48Speaker 1: you use the pgr nl macro to check if a
- 22:52Speaker 1: specific argument is NLL before you try to access its
- 22:55Speaker 1: value with pg turner, and if you need to return
- 22:58Speaker 1: NL you use pgr turnal forgetting. This as a common
- 23:01Speaker 1: source of crashes, C is less forgiving.
- 23:03Speaker 2: What about very attic arguments.
- 23:05Speaker 1: Those arrive in your CE function as a Postgres school
- 23:08Speaker 1: array type. You need to use specific C functions to
- 23:10Speaker 1: deconstruct that array, getting its dimensions, checking its element type,
- 23:14Speaker 1: and then iterating through the elements. A bit more work
- 23:16Speaker 1: than in popg sqel.
- 23:18Speaker 2: Memory management must be crucial in SEA leaks.
- 23:20Speaker 1: Crashes absolutely vital. You must use postgrescols memory management functions
- 23:24Speaker 1: primarily pallic and free, not standard Sea mallek and free.
- 23:28Speaker 1: Palic allocates memory within postgres School's current memory context. The
- 23:33Speaker 1: beauty is that memory allocated in shorter lived contexts like
- 23:36Speaker 1: the protuple or perfunction call context, is automatically freed when
- 23:41Speaker 1: that context is destroyed. This prevents many common memory leaks.
- 23:44Speaker 1: Ah that's clever it is and always zero fyll allocated
- 23:48Speaker 1: structures using memset to avoid subtle bugs from uninitialized memory.
- 23:52Speaker 1: For air reporting, you don't just print. You use postgres
- 23:55Speaker 1: School's air function dot airport is very structured. You specify
- 23:59Speaker 1: at the severity level error warning notice, log et cetera,
- 24:03Speaker 1: and soul state code, primary message detail hint. It handles
- 24:07Speaker 1: localization and routes the message correctly to client or log
- 24:11Speaker 1: error level aborts the current transaction. Importantly, unlike exceptions in
- 24:15Speaker 1: plpg sql, air report messages are generally sent to the
- 24:18Speaker 1: client immediately, not buffered until the end of the function.
- 24:21Speaker 2: Okay, and how do these C functions run SQL queries
- 24:25Speaker 2: back into.
- 24:25Speaker 1: The database that's done using the SBI, the server programming interface.
- 24:29Speaker 1: Inside your C function, you call SBI connect that you
- 24:32Speaker 1: can execute queries using functions like spy ASEC or SPIKESIGI
- 24:35Speaker 1: plan for prepared statements. You process the results, and critically,
- 24:38Speaker 1: you must call SBI finish before your C function returns.
- 24:42Speaker 1: SBI handers transaction context correctly, but understanding data visibility rules.
- 24:46Speaker 1: What changes your function can see from other transactions or
- 24:49Speaker 1: even earlier commands within the same transaction is important for
- 24:52Speaker 1: complex scenarios, so.
- 24:54Speaker 2: C offers the ultimate power what other advanced things become possible.
- 24:58Speaker 1: You can do some really sophistic icated stuff. Write extremely
- 25:02Speaker 1: high performance triggers in C for logging changes with minimal overhead.
- 25:06Speaker 1: Register C functions to be called automatically on command or
- 25:10Speaker 1: on rollback of a transaction. Great for cleanup or post
- 25:13Speaker 1: commit actions. You can even interact directly with postcres schools
- 25:16Speaker 1: shared memory and use lightweight locks for synchronization between different
- 25:20Speaker 1: back end processes, enabling complex interprocess communication managed by the database. Honestly,
- 25:26Speaker 1: the best way to learn advanced SEA extension techniques.
- 25:29Speaker 2: Is let me guess.
- 25:30Speaker 1: Use the source looke aha exactly. Look at the code
- 25:33Speaker 1: for Postcrescol's own contrip modules. They cover a huge range
- 25:36Speaker 1: of examples, from custom data types to procedural languages. It's
- 25:39Speaker 1: all there, open source, ready to be studied, hashtag tag
- 25:42Speaker 1: tax stealing your database with po proxy and polishing extensions.
- 25:45Speaker 2: Okay, let's shift focus again. We've built these powerful functions,
- 25:48Speaker 2: maybe even in c our single server is humming. But
- 25:51Speaker 2: what happens when the load gets truly massive? How do
- 25:53Speaker 2: you scale postcrescool horizontally?
- 25:55Speaker 1: Right? So you've optimized your single server, added indexes, tune queries,
- 25:59Speaker 1: maybe even us some of those c functions, but your
- 26:02Speaker 1: database is still creaking under the load. Maybe CPU is
- 26:06Speaker 1: pegged at eighty percent plus four hours a day. Traditional
- 26:10Speaker 1: scaling options have limits buying bigger server Vertical scaling gets expensive.
- 26:14Speaker 1: Fast master slave replication helps with read loads, but not
- 26:18Speaker 1: write loads. Multi master replication adds complexity for really heavy workloads,
- 26:24Speaker 1: especially right heavy ones. Horizontal partitioning or scharding becomes the
- 26:28Speaker 1: logical step. You split your data across multiple independent postgress
- 26:32Speaker 1: wile servers partitions.
- 26:34Speaker 2: How do you manage that split? Doesn't that make the
- 26:36Speaker 2: application logic way more complex?
- 26:38Speaker 1: It can if you're not careful that's where proxy databases
- 26:40Speaker 1: come in. The application talks to a proxy layer which
- 26:43Speaker 1: knows how to route queries to the correct data partitions.
- 26:46Speaker 1: This keeps the partitioning logic transparent to the application itself.
- 26:49Speaker 2: Okay, let's ground this. You mentioned a chat application example earlier. Yah,
- 26:53Speaker 2: how did optimization play out before even thinking about charting?
- 26:56Speaker 1: Yeah, the example started with simple user info and message
- 26:59Speaker 1: table and basic functions user log in, send message, et cetera. Initially,
- 27:05Speaker 1: fetching just seven new messages took something like seven or
- 27:08Speaker 1: and sixty milliseconds pretty slow. But then just by adding
- 27:11Speaker 1: the right indexes on foreign keys and message time stamps,
- 27:14Speaker 1: and crucially setting the fill factor on the message table
- 27:17Speaker 1: to allow for hot t.
- 27:18Speaker 2: Updates, stay shot TA updates, keep.
- 27:20Speaker 1: Only touple updates. It's a postgres will optimization where if
- 27:23Speaker 1: an update doesn't change any index columns, postcres can sometimes
- 27:26Speaker 1: update the road directly in place on a data page
- 27:29Speaker 1: without needing a new index entry. It massively reduces right
- 27:32Speaker 1: overhead for certain update patterns. Just those changes brought the
- 27:35Speaker 1: query time down from seven to sixty meters to under
- 27:37Speaker 1: three meters, and then with further tuning down to about
- 27:39Speaker 1: one point nine meters, a huge improvement without adding any servers.
- 27:43Speaker 1: Always optimize first.
- 27:45Speaker 2: Good point. But okay, say we do need to shard.
- 27:47Speaker 2: How do we split the data?
- 27:48Speaker 1: You need a partitioning key. If you have integer primary keys,
- 27:52Speaker 1: a simple modul operation like user in three bitwise and
- 27:56Speaker 1: d with three equivalent to modulo four for positive numbers
- 27:59Speaker 1: can distribute users across four partitions. If your key is
- 28:02Speaker 1: text like a username, you typically hash it first hashtext
- 28:06Speaker 1: username and then apply the modular to the resulting integer
- 28:09Speaker 1: hash for even distribution. And to manage the routing from
- 28:12Speaker 1: the proxy to these partitions, postgrescool has a specialized tool,
- 28:16Speaker 1: peel proxy.
- 28:17Speaker 2: Another procedural language YEP, but this one isn't for general logic.
- 28:21Speaker 1: It's specifically designed for database charding. You install like any
- 28:24Speaker 1: other language, create extension pal proxy.
- 28:26Speaker 2: How does it syntax work? How do you tell it
- 28:28Speaker 2: where to send in the queries?
- 28:29Speaker 1: It's quite declarative. Inside a peel proxy function, you use
- 28:33Speaker 1: connect to specify the connection string for a remote database partition.
- 28:38Speaker 1: You can group these connections into named clusters. Then the
- 28:41Speaker 1: core is the r on clause you tell it which
- 28:44Speaker 1: partitions to run the remote function on. This could be
- 28:47Speaker 1: based on a routing function partition, part funk user, or
- 28:50Speaker 1: you can specify any run on any single partition, maybe
- 28:53Speaker 1: for reads that could be anywhere or all, run the
- 28:56Speaker 1: function in parallel on all partitions. Perhaps for broadcasting a command.
- 29:00Speaker 1: You also specify the remote function call using select or target.
- 29:03Speaker 2: Okay, it seems logical. You mentioned parallel execution with run
- 29:06Speaker 2: on all.
- 29:07Speaker 1: Yeah. And there's also the spli statement, which is really
- 29:10Speaker 1: powerful for distributing bulk operations. Imagine a function create users
- 29:15Speaker 1: that takes a raise of usernames, passwords, and emails. You
- 29:18Speaker 1: can write a pl proxy function that uses SPLT to
- 29:21Speaker 1: take these arrays, figure out which partition each new user
- 29:24Speaker 1: belongs to based on their username hash, and then efficiently
- 29:27Speaker 1: send batches of users to the correct partitions in parallel.
- 29:30Speaker 1: Very slick.
- 29:30Speaker 2: How does pl proxy know about the cluster members?
- 29:33Speaker 1: Two main ways. The older way uses special configuration functions
- 29:37Speaker 1: like plproxy dot get cluster partitions that you define to
- 29:40Speaker 1: return the connection strengths. The more modern and generally recommended
- 29:44Speaker 1: way is to use sql MED, the standard SQL management
- 29:47Speaker 1: of external data features. You create foreign data wrapper pull proxy,
- 29:52Speaker 1: then create server for each partition and create user mapping
- 29:55Speaker 1: to store credentials securely pl proxy, then queries these standard
- 29:59Speaker 1: caps objects define the cluster configuration right.
- 30:02Speaker 2: And migrating existing data.
- 30:04Speaker 1: Usually involve setting up the schemas on the partitions, then
- 30:07Speaker 1: carefully copying data row by row or chunk by chunk,
- 30:10Speaker 1: using the partitioning key to determine the destination. It could
- 30:13Speaker 1: be complex for live systems. It's careful planning.
- 30:16Speaker 2: Okay, so we've staled out. Now let's talk about sharing
- 30:18Speaker 2: all this cool stuff. We might have built custom functions, types, operators.
- 30:22Speaker 2: Why package them as a postcrischool extension. What's the benefit
- 30:26Speaker 2: over just shipping seql scripts?
- 30:27Speaker 1: So extensions are a massive improvement over the bad old
- 30:30Speaker 1: days of just providing dishquare yell files like the old
- 30:32Speaker 1: contrip modules.
- 30:33Speaker 2: Why were those bad?
- 30:34Speaker 1: They had no concept of dependencies, no versioning, no clean installation,
- 30:38Speaker 1: and crucially no upgrade path. If you install version one
- 30:42Speaker 1: of a script and a version two came out that
- 30:44Speaker 1: changed a function signature or a table definition, you often
- 30:47Speaker 1: had to manually drop everything from version one, losing data,
- 30:50Speaker 1: and then load version two. Painful yikes. And extension solves
- 30:54Speaker 1: all this. It's a formal package containing all related sequl objects, functions, tables, views, types,
- 30:59Speaker 1: operators can figuration parameters. To install it with single command
- 31:02Speaker 1: create extension my extension. Postgrescool tracks the installed objects as
- 31:06Speaker 1: belonging to that extension and the killer feature upgrades. If
- 31:10Speaker 1: you release version two point oh you provide an extension
- 31:13Speaker 1: one point two point oh dot s well update script.
- 31:16Speaker 1: Users just run ulter extension my extension update and postcrescool
- 31:19Speaker 1: applies the necessary changes cleanly, preserving data. Extensions can also
- 31:23Speaker 1: declare dependencies on other extensions.
- 31:25Speaker 2: That sounds much much better. How do you build one again?
- 31:29Speaker 1: You typically use the PGXS build system with a simple makefile.
- 31:32Speaker 1: It handles compiling any c code and packaging the SQL
- 31:35Speaker 1: files correctly. Pseudo make install puts it where postgrescool can find.
- 31:38Speaker 2: It and sharing it.
- 31:39Speaker 1: You publish it to the Postgres School Extension Network PGXN
- 31:43Speaker 1: PGXN dot org. There are tools like pgx and utails
- 31:46Speaker 1: to help package your extension correctly. You need a metada
- 31:49Speaker 1: adjacent file describing your extension, its licensed dependencies, and crucially
- 31:54Speaker 1: it's version number. Using semantic versioning, this allows users to
- 31:57Speaker 1: easily search for, download and install all extensions using clients
- 32:01Speaker 1: like PGX and client. It really makes postgress will incredibly
- 32:04Speaker 1: extensible and inviting for the open source community. Compared to
- 32:08Speaker 1: other databases, this standardized, robust extension system is well pretty revolutionary.
- 32:13Speaker 1: It makes it easy for anyone to extend postgreds to
- 32:15Speaker 1: do almost anything they want. Hashtag taghtag outro eerro.
- 32:18Speaker 2: Wow, we've covered a ton today. We really have taken
- 32:21Speaker 2: a deep dive into POSTGRESSWIL server programming. It's clear it
- 32:23Speaker 2: transforms the database from just you know, storage into a
- 32:26Speaker 2: really dynamic application development framework. From the basics of peelpgseql,
- 32:30Speaker 2: through the power and risks of Peel, Python and see
- 32:33Speaker 2: and even scaling out horizontally with Peel proxy. The common
- 32:36Speaker 2: thread is pushing logic closer to the data, and that
- 32:38Speaker 2: leads to apps that are faster, definitely more secure, and
- 32:41Speaker 2: easier to maintain.
- 32:42Speaker 1: Absolutely, and we just sort of zoom out for a
- 32:44Speaker 1: final thought. In a world that's increasingly driven by data,
- 32:48Speaker 1: really understanding and using these service side capabilities isn't just
- 32:51Speaker 1: another technical skill. It's more like paradigm shift, you know,
- 32:54Speaker 1: a different way of thinking about where your critical logic
- 32:57Speaker 1: should live, which maybe raises a question for you listening
- 33:01Speaker 1: right now. What untapped potential, what hidden power are you
- 33:05Speaker 1: overlooking in your current database solutions by treating them as
- 33:08Speaker 1: just simple data buckets